Blog

  • Home /
  • Blog /
  • Taking Toddler Steps with Node.js - Express Error Handling

Taking Toddler Steps with Node.js - Express Error Handling

April 6, 2012

In the previous post I wrote about my personal routing flavor for Express. For this post, I want to briefly discuss how to set up error handling using Express.

In order to get up and going very quickly, we only need to add the errorHandler middleware provided by Connect.

Here we configured the errorHandler middleware to report on exceptions and show the stack trace as well. This is quite handy during development as this setup provides us with enough detail.

image

But this is not very effective when we want to move our application to a production environment. When deployed into production, we usually want to show a user-friendly message instead of technical details, stack traces and what not. In this case we can use the application.error() method. This function receives all errors thrown by the regular route functions or errors passed to the next() function. In this catch-all-errors function we can simply render our own custom view.

This is how our custom error page looks like:

image

We can also use the application.error() function for rendering custom pages for all kinds of specific errors. Suppose we want to render a custom page for ‘404 – Page Not Found’ errors. Quite easy. We just need to register a catch-all route after all the regular route functions that simply throws a custom error.

Next we need to enhance application.error() function so that it appropriately handles our PageNotFoundError.

application.use(express.errorHandler({ showStack: true, dumpExceptions: true }));

As you can see, error handling is quite easy to setup for different environments using Express.

Until next time.

If you and your team want to learn more about how to write maintainable unit tests and get the most out of TDD practices, make sure to have look at our trainings and workshops or check out the books section. Feel free to reach out at infonull@nullprincipal-itnull.be.

Profile picture of Jan Van Ryswyck

Jan Van Ryswyck

Thank you for visiting my blog. I’m a professional software developer since Y2K. A blogger since Y2K+5. Provider of training and coaching in XP practices. Curator of the Awesome Talks list. Past organizer of the European Virtual ALT.NET meetings. Thinking and learning about all kinds of technologies since forever.

Comments

About

Thank you for visiting my website. I’m a professional software developer since Y2K. A blogger since Y2K+5. Author of Writing Maintainable Unit Tests. Provider of training and coaching in XP practices. Curator of the Awesome Talks list. Thinking and learning about all kinds of technologies since forever.

Contact information

(+32) 496 38 00 82

infonull@nullprincipal-itnull.be