Create a Simple API:
Handling Errors & Improving the Project Setup (Video 4)

This tutorial is based exclusively on Maximillian Schwarzmüller's Creating a REST API with Node.js starting with Part 3 Handling Errors & Improving the Project Setup. It shows just the coding occurring in video 4.

  1. In the node directory, install nodemon: npm --install-dev nodemon.
  2. Open package.json, and add this line just below "test": "start": "nodemon server.js". You may have to add a {} (left brackets) so that keywords looks like this
    "keywords": ["nodejs",
        "restful",
        "api"
      ],
  3. At the commend line, enter npm start. (I get an error here which I have not figured out.)
  4. To see logging messages, install morgan: npm --install-save morgan. (Errors here also.)
  5. Open app.js and just below the const app line, add const morgan = require('morgan');
  6. Still in app.js, just below the const orderRoutes line, add app.use(morgan('dev'));
  7. Also to app.js, below the app.use('/orders line, enter these lines:
    app.use((req, res, next) => {
        const error = new Error('Not found');
        error.status(404);
        next(error);
    })
    
    app.use((error, req, res, next) => {
        res.status(error.status || 500);
        res.json({
            error: {
                message: error.message
            }
        });
    });
    
  8. Create some errors.