For a long time now, I’ve been brute-force ugly with my error handling in my ExpressJS apps. Basically, just throw the exception after it bubbles back up to the route handler.
This works. If you don’t mind the app completely blowing chunks at this point and dumping itself entirely.
Of course, you could put a global error handler in your code to catch this unhandled exception, and *not* exit the app. But this is probably a bad idea, too. Once an exception is thrown (and not handled by the code that was being called, in the first place), the NodeJS environment is basically in an unknown and potentially bad state.
Handle It Properly
Unhandled exceptions should not be allowed to crash and exit the app. Therefore, you really want to handle this exception in your callback, properly.
It’s a simple change, but using “return next(err);” instead of “throw err;” allows asynchronous code to raise an exception and still have it caught by the error handling pipeline in your app. Instead of putting the app into an unknown state where everything is potential dead or dangerous, calling “next(err)” tells the Express and Connect frameworks to pass the error along until an error handling middleware of function can properly take care of it.
Error Handler Middleware
If you weren’t aware of it, every ExpressJS app comes with an error handler (or two – one for development work, one for non-development work… “production” … by default) in the default app.js file that is generated by the express command line:
This code properly handles an error that was sent up the line using the “return next(err);” style of handling. Instead of putting the app in to an exception state by throwing the error, it is properly handled by the middleware, allowing you to write your own custom code, error logging and rendered view in response to the error ocurring.
More On Error Handling
There are potentially a lot more advantages to doing things this way, centered around application design and code architecture. But I’ll leave those for other discussions.
If you want to read more about proper error handling, check out this article on error handling in NodeJS, from Joyent (thanks to Peter Lyons for pointing this one out):
— Peter Lyons (@focusaurus) September 6, 2014
Now if you’ll excuse me for a moment, I’ve got to go clean up some error handling code in my apps.
P.S. Check out the WatchMeCode Screencast on Error Handling in Express, to see this in action!