Error Handling

One last job remains. When a file cannot be found, it is better to return an error code than to silently pretend that all is well. To do that, you will need to detect when fs.readFile returns an error instead of a file.

In JavaScript, it is common to pass callbacks to API methods. The same is true for Node.js, and callbacks typically take in an error as their first argument. Because the error comes before the result, you are forced to at least see the error, whether or not you handle it.

In index.js, check for a file error and write a 404 error code if one is found:

var http = require('http');
var fs = require('fs');
var extract = require('./extract');

var handleError = function (err, res) {
  res.writeHead(404);
  res.end();
};

var server = http.createServer(function (req, res) {
  console.log('Responding to a request.');
  var filePath = extract(req.url);
  fs.readFile(filePath, function (err, data) {
    if (err) {
      handleError(err, res);
      return;
    } else {
      res.end(data);
    }
  });
});
server.listen(3000);

Save your changes. After nodemon restarts, go to a nonexistent path, such as http://localhost:3000/woohoo. Open the network panel in the DevTools, and you should see the error code, as in Figure 15.14.

Figure 15.14  404 Status code in the network panel

404 Status code in the network panel

In your callback, the very first thing you do is check whether this err argument has a value that is not null or undefined and do something with it. In this example, you pass the error information along to the function handleError and then return to exit the anonymous callback.

Errors should never be silently discarded. A simple 404 will do fine for now, which is what handleError does.

This pattern – “errors first, return early” – is one of the best practices that is a part of the Node ecosystem. All of the modules that come with Node follow this pattern, as do most open-source modules.

You have built a working web server with just a few dozen lines of JavaScript, using patterns (such as callbacks) that you were already familiar with.

Node provides a rich set of modules for working with networks and files, such as the http and fs modules you used in this project. Thanks to Node’s require and module.exports keywords, you can modularize your own code very easily.

Over the next three chapters, you will continue to build the Chattrbox server as well as a working front end.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.14.144.216