I generally try to avoid using try-catch. Error handling is not something I like to see scattered across my code base. Node also considers this and throwing errors to be bad practice.
The express framework can be configured to handle errors through the use of 'app.use'. Express considers any middleware with 4 args as error middleware. This also allows us; if we so wish to configure environment based error handling; which is useful if in production you would like to log errors.
Here is our error handler for checking if the 'IsNotAuthenticated' error has been passed; the handler in this case redirects to the login page.
Now lets define a route which requires authentication.
Any requests to the above route will be sent through to the below piece of route middleware, which checks if the user is logged in; passing the 'IsNotAuthenticated' error if no session is found.
Lets revisit the first code sample; this 'configure' block allows us to setup multiple error handlers; handling different types of error.
This is how express handles different error types; if a handler is unable to handle the error passed in; the error is passed onto the next handler.
For example the first error handler below checks if the error is of a given type and handles it; if the type does not match; the next error handler is called. Express will continue this process calling middleware methods with 4 arguments until the error is handled.
This post is part of a series of posts tagged under node-plates a boilerplate mobile/web application written in node.js, express, socket.io, mongooose, jquery.mobile & html 5.
You can grab this from github ->