1×
Become a member
to unlock all features

Level Up!

Access all courses & lessons on egghead today and lock-in your price for life.

Autoplay

    Add Basic Error Handling to an Express 5 App

    expressExpress

    In this lesson you'll learn how to add a custom 404 handler to your express app. You'll also learn how to define a general error handler that is called when any of your routes or middleware have errors.

    Express provides an excellent reference on error handling in express on the Express website.

    404 Handler

    A 404 error handler is basically a route handler defined after all of the others without a path associated with it. These handlers naturally become a catchall for any request that isn't handled by existing routes. You define it like this:

    app.use(function(req, res) {
         res.status(404).send("Not Found");
    });

    Read more in the express API doc.

    Error Handler

    Express allows you to register a general error handler that catches any errors thrown in the course of running your application* including both routes and middlewares. It's common to think of this as your 500 error handler, which is the HTTP status code for Internal Server Error. Think of this as something going wrong that is not the users fault.

    To register the error handler call app.use with a function taking these 4 arguments: err, req, res, next as in this short example:

    app.use(function(err, req, res, next) {
        console.error(err.stack); // log the error to the STDERR
        res.send(err.message); // send back a friendly message to the client
    })

    Note: express error handlers can't usually catch errors thrown in an async callback function such as a setTimeout call or process.nextTick function. Errors thrown in these situations will typically crash your server.