Lesson 11. Configurations and error handling

In lesson 10, you added Embedded JavaScript (EJS) to your application views. In this lesson, you add finishing touches to your application by modifying your package.json file to use a start script. This script changes the way that you start your application from terminal. Then you add error handling middleware functions to log errors and respond with error pages.

This lesson covers

  • Changing your application start script
  • Serving static pages with Express.js
  • Creating middleware functions for error handling
Consider this

You’re in full swing developing your recipe application. As is common in programming, you run into many errors, but you have no clear indication of those errors in your browser.

In this lesson, you explore ways to serve error pages to your browser window when appropriate.

11.1. Modifying your start script

To start this lesson, you modify a file that you haven’t touched in a while. The package .json file is created every time you initialize a new Node.js application, but you’ve changed hardly any of its values manually. In lesson 4, I talked about using the npm start command to start your application when that script is configured in your project’s package.json.

Make a copy of your express_templates application folder from lesson 10. In your -package.json file, locate the scripts property; you should see a placeholder for a test script. Add a comma to the end of that test script, and add "start": "node main.js". This script allows you to run npm start to start your application and abstracts the need to know the name of your main application file. That part of your package.json file should look like the next listing. Within the scripts object, you can use the key—start—to start your application by running npm start, npm run start, or npm run-script start.

Listing 11.1. Add the npm start script to your package.json
"scripts": {
  "test": "echo "Error: no test specified" && exit 1",
  "start": "node main.js"                                     1
},

  • 1 Add a start script to package.json.

Save your file, and run your application with npm start. Functionally, nothing else should change in your application, which should start as usual.

Tip

If you experience any issues restarting your application, try reverting to node main to rule out any accidental changes made in your main.js file.

In the next section, you improve the way that you handle errors in your application.

Quick check 11.1

Q1:

What’s the purpose of the scripts object in your package.json file?

QC 11.1 answer

1:

The scripts object allows you to define aliases for commands that you want to run with npm.

 

11.2. Handling errors with Express.js

So far, Express.js has been a great improvement on the development process. One perk is that the application doesn’t hang forever when a request is made to a path for which no route exists. When you make a request to the home page, however, if there’s no route to handle that request, you see an unfriendly Cannot GET / in your browser.

You can take a few approaches to error handling with Express.js. The first approach is logging to your console whenever an error occurs. You can log errors the same way that you logged the requested path in lesson 10. Because I’m dealing with a topic that’s separate from serving normal informational pages, I recommend that you create a new controller and install the http-status-codes package by running npm install http-status-codes --save in the project’s terminal window.

Create errorController.js in your controllers folder, and add the function shown in listing 11.2. This function contains one more argument than the normal middleware function. If an error occurs in the request-response cycle, it appears as the first argument. As with console.log, you can use console.error to log the error object’s stack property, which tells you what went wrong. As in the previous middleware functions, the next argument calls the next function or route in the chain, this time passing the error object in case it needs to be processed further.

Note

You need to accept four arguments in this error handler, with the first argument always representing the error object. Without all four arguments, the function will not be interpreted as error handling middleware, but instead as a normal middleware function..

Listing 11.2. Adding a function to your error controller, errorController.js
exports.logErrors = (error, req, res, next) => {      1
  console.error(error.stack);                         2
  next(error);                                        3
};

  • 1 Add middleware to handle errors.
  • 2 Log the error stack.
  • 3 Pass the error to the next middleware function.
Tip

Using console.log is great for general debugging, but as your application gets more involved, you’ll want to vary your log messages. Tools such as the Chrome browser’s console window can color-coordinate these messages for you to distinguish between general log messages and error messages.

Next, you need to tell Express.js to use this middleware function by requiring errorController.js and adding app.use(errorController.logErrors) to your main.js file. You can invoke an error by commenting out the line that defines the paramsName variable in the respondWithName function. Then, when you visit http://localhost:3000/name/jon, your logErrors function will run. Remember to uncomment that line when you’re done.

Warning

Make sure to add the middleware line in main.js after the rest of your normal route definitions.

By default, Express.js handles any errors at the end of processing a request. If you want to respond with a custom message, however, you can add a catch-all route at the end of your routes to respond with a 404 status code if the page is not found or a 500 status code if your application got an error in the process. That code should look like listing 11.3 in errorController.js.

In errorController.js, the first function responds with a message to let the user know that the request page wasn’t found in your routes. The second function notifies the user of an internal error that prevented the request from being processed. Here, you use the http-status-codes module in place of the code values themselves.

Listing 11.3. Handle missing routes and errors with custom messages in errorController.js
const httpStatus = require("http-status-codes");

exports.respondNoResourceFound = (req, res) => {                1
  let errorCode = httpStatus.NOT_FOUND;
  res.status(errorCode);
  res.send(`${errorCode} | The page does not exist!`);
};
exports.respondInternalError = (error, req, res, next) => {     2
  let errorCode = httpStatus.INTERNAL_SERVER_ERROR;
  console.log(`ERROR occurred: ${error.stack}`)
  res.status(errorCode);
  res.send(`${errorCode} | Sorry, our application is
experiencing a problem!`);
};

  • 1 Respond with a 404 status code.
  • 2 Catch all errors and respond with a 500 status code.

In main.js, order matters. respondNoResourceFound will catch requests made with no matching routes, and respondInternalError will catch any requests where errors occurred. Add these middleware functions to main.js, as shown in the following listing.

Listing 11.4. Handle missing routes and errors with custom messages: main.js
app.use(errorController.respondNoResourceFound);           1
app.use(errorController.respondInternalError);

  • 1 Add error-handling middleware to main.js.

If you want to customize your error pages, you can add a 404.html and a 500.html page in your public folder with basic HTML. Then, instead of responding with a plain-text message, you can respond with this file. This file won’t use your templating engine to process the response. Your respondNoResourceFound function in your error controller looks like the next listing. In this code, res.sendFile allows you to specify an absolute path to your error page, which is helpful if your normal templating renderer isn’t working.

Listing 11.5. Handle missing routes and errors with custom messages
exports.respondNoResourceFound = (req, res) => {       1
  let errorCode = httpStatus.NOT_FOUND;
  res.status(errorCode);
  res.sendFile(`./public/${errorCode}.html`, {         2
    root: "./"
  });
};

  • 1 Respond with a custom error page.
  • 2 Send content in 404.html.

Now that you have error messages being served to your users and logged to your terminal, you should make sure that your application is set up for serving static files like your 404.html page.

Quick check 11.2

Q1:

Why does your middleware that handles missing routes go after your nor-mal application routes?

QC 11.2 answer

1:

The middleware function that responds with 404 status codes acts like an else inand if-else code block. If no other route paths match the request, this function responds with the message to your user.

 

11.3. Serving static files

This last section is a short one. In your application from unit 1, serving all different types of static files and assets would require hundreds of lines of code. With Express.js, these file types are accounted for automatically. The only thing you need to do is tell Express.js where to find these static files.

Note

Static files include your assets and custom error pages, such as 404.html and 500.html. These HTML pages don’t go through a templating engine because they don’t contain any EJS values.

To set up this task, you need to use the static method from the express module. This method takes an absolute path to the folder containing your static files. Then, as with any other middleware function, you need to tell the Express.js app instance to use this feature. To enable the serving of static files, add app.use(express.static("public")) to main.js. This line of code tells your application to use the corresponding public folder, at the same level in the project directory as main.js, to serve static files.

With this code in place, you can visit http://localhost:3000/404.html directly. You can also place an image or another static asset in your public folder and access it by filename after the main domain in your URL. If you add an image, such as cat.jpg, within another subdirectory called images, you can view that image alone by visiting http://localhost:3000/images/cat.jpg.

Quick check 11.3

Q1:

What important static files live in your public folder?

QC 11.3 answer

1:

Your public folder contains static HTML files for your error pages. If some-thing goes wrong in your application, these files can be served back to the client.

 

Summary

In this lesson, you learned how to change your application’s start script. You also learned how to log and manage some of the errors that occur in your Express.js application. At the end of the lesson, you set up Express.js to serve static assets from your public folder. Now you have quite a few tools at your disposal to use in building your recipe application. In lesson 12, you put what you’ve learned to the test by restructuring the Confetti Cuisine application.

Try this

Now that you have the ability to serve static files, build a creative HTML page for 404 and 500 errors in your application. These files don’t use the normal layout file that you use for templating, so all your styling must live inside the HTML page.

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

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