Posted by & filed under Content - Highlights and Reviews, Programming & Development.

codeA guest post by Roman Shtylman, founder of Courseoff, an online student scheduling tool. Courseoff uses Express.js for all their web services. He has been involved in open source for many years and is a contributor to many open source projects, Express.js being one of them. His current development passion is for JavaScript and Node.js and he frequently evangelizes new tools and techniques in the JavaScript ecosystem. He can be found on Twitter @defunctzombie.

Handling errors is an important aspect of any library or application and Express.js applications, whether they be full web sites or just API services, are no exception. Built into the Express.js middleware workflow is an often overlooked feature that can greatly simplify your error handling. This post will clarify how error handling works in Express.js applications, and how it can be leveraged to write less code to do more. A basic understanding of Express.js and routing will help you get the most from this post.

If you haven’t read it already, be sure to look at my Express.js Middleware Demystified post.

Basic error handling

To demostrate how error handling works, we will use it to handle 404 requests. Such requests happen when you have no route to handle the requested resource.

First, let’s start with a simple Express.js app:

If we put the JavaScript above into a file server.js and run it via node server.js, we can open our web browser to http://localhost:3000 and see the text hello world appear.

What happens, however, when a user visits http://localhost:3000/catpics? The default Express.js app will simply return Cannot GET /catpics. A common theme across websites is to provide custom 404 pages. While a 404 may not strictly be an “error,” we will still show how to leverage error handling to print a custom 404 page.

Let’s see what this error handling middleware will look like:

If you now run server.js and visit /catpics, you will see the custom message no unicorn here.

Understanding 404 error handling

The first thing we added was a new route with a path *. This means that for any GET request not already handled, use this route. It is important that this route be added last, otherwise it will prevent a real request from being handled.

Inside of the route handler you make a new error object and add a status property to it. Then you pass this error object to the next argument by invoking it as a function. next is an argument provided by Express.js in addition to req and res as a way to “pass along” control to the next middleware (or route). If you simply invoke next(), it will try to run the next middleware; however in this example you pass an Error instance to next, which makes it behave differently!

When you pass an Error to next, Express.js will not jump to the next route or middleware, but will instead jump to processing what is known as error middleware.

Error middleware vs Normal middleware

Error middleware is differentiated from regular middleware/routes by their characteristic four argument functions: err, req, res and next. When defining any sort of error middleware you MUST name all four function arguments, otherwise Express.js will not be able to tell this is error middleware, and will attempt to treat this middleware like all other middleware.

When our /catpics request was processed, and Express.js found no route to handle it, it fell to the * handler, which created an Error object and invoked next with this error. This caused Express.js to skip any other routes/middleware and jump straight to our error middleware and respond with a custom message.

Not that our error middleware checks that the error status is 404 before sending a response. If the status is not 404 then it too calls next(), which passes processing to the next error middleware available (in this case there is no other error middleware).

This starts to really simplify your code workflow when you have many routes (some possibly loading database assets, etc).

Such code is common in applications that need to make further API or database requests. Instead of responding to each error within the route, simply use next to pass along an error or a 404 status and invoke the error handlers. To work with the simple example above, you would add one more error handler under the existing 404 handler.

Now, whenever you call next(err) inside any route handlers, you will start to process via the error handling routines. This provides a consolidated, single point of error processing for the application.

Conclusion

You should now have a better handle on how to take advantage of error handling in Express.js. Keep in mind that error handlers are typically last (after all other middleware and routes), and you can have more than one error handler (as showed with the 404 handler).

For further information take a look at the Express.js error handling docs and be sure to spend some time examining the great books below that cover Express.js from Safari Books Online.

Not a subscriber? Sign up for a free trial.

Safari Books Online has the content you need

Professional Node.js: Building Javascript Based Scalable Software begins with an overview of Node.js and then quickly dives into the code, core concepts, and APIs. In-depth coverage pares down the essentials to cover debugging, unit testing, and flow control so that you can start building and testing your own modules right away.
JavaScript Programming: Pushing the Limits delivers a compelling tutorial, showing you how to build a real-world app from the ground up. Experienced developers who want to master the latest techniques and redefine their skills will find this deep dive into JavaScript’s hidden functionalities gives them the tools to create truly amazing and complex applications.
Smashing CoffeeScript is a full-color, practical book that explains the CoffeeScript language, syntax, and processes, and will soon have you producing concise and quality code. Ultimately, you’ll create RIAs and mobile apps faster, with less hassle.
Node.js Recipes: A Problem-Solution Approach is your one-stop reference for learning how to solve Node.js problems. Node.js is the de facto framework for building JavaScript-powered servers. You will first be introduced to this exciting technology and what it can do, then learn through comprehensive and easy-to-follow recipes that use a problem-solution approach. This book teaches you to fully use the Node.js API, and leverage existing modules to build truly exciting projects.

Tags: Error Handling, Express.js, GET, middleware, routes,

2 Responses to “Error Handling in Express.js Applications”

  1. mize

    Nice post! In the “Error middleware vs Normal middleware” section, I think the missing pic conditional should read:


    if (!pic) {
    var notFound = new Error('no such catpic');
    notFound.status = 404;
    next(notFound);
    }

  2. Raheel

    Shouldn’t the last pic condition block have a return as well?

    if (!pic) {
    var notFound = new Error('no such catpic');
    notFound.status = 404;
    return next(notFound);
    }