Lab: Error Handling

  • In this lab, we customize the launch NodeJS app via package.json and develop error handling code in Express controller.
  • You can begin the lab via the start directory of Lesson 11 source code
  • You can cross check the final result in the finish directory.

Step 1: Custom launch

1
2
3
4
"scripts": {
  "test": "echo \"Error: no test specified\" && exit 1",
  "start": "node main.js"                                     1
},

Step 2: Error handling in Express

Error handling approaches with Express
  1. Logging to console (console.log) whenever an error occurs.
  2. (Recommended) Creating a new controller and install the http-status-codes package
Setup error controller
  • Install http-status-codes
1
npm install http-status-codes --save
  • Create errorController.js in the controllers folder with the following contents (Listing 11.2 from the book)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
"use strict";

const httpStatus = require("http-status-codes");

exports.logErrors = (error, req, res, next) => {
  console.error(error.stack);
  next(error);
};

exports.respondNoResourceFound = (req, res) => {
  let errorCode = httpStatus.NOT_FOUND;
  res.status(errorCode);
  res.send(`${errorCode} | The page does not exist!`);
};

exports.respondInternalError = (error, req, res, next) => {
  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!`);
};
Exercise
  • Look at the main.js in Lesson 11 and compare that with main.js in Lesson 10.
  • Examine the additional middleware layer added to handle error
Exercise
  • Play with the static HTML file in the public directory inside finish and see the responses.

Step 3: Capstone Lab