• Join StackChief
  • Blog
  • Tutorials
  • Questions
  • React
  • JavaScript
  • MongoDB
  • NodeJs
  • Kafka
  • Java
  • Spring Boot
  • Examples

Blog

Express Error Handling: Tips & Tricks

Express uses middleware to simplify error handling. Writing middleware is fairly straight forward, however existing documentation doesn't clearly explain how to get started with built in error handling. The following is a complete example with supporting tips and tricks for good error handling with Express.

app.get('/endpoint', function(req,res,next){
var error = {message:'example error!'}
next(error);
})

app.use(function(err,req,res,next){
res.json(err)
})

This is a very basic example of using error handling with Express. It's important to point out a few things that can trip up developers.

It's just middleware

If you're familiar with writing middleware, then you know that functions typically take three arguments (req,res,next). The next argument is really a function that calls the next handler in the request chain.

Error handling middleware is the exact same, except for an additional err parameter. This is the first parameter and represents the error object. Instead of (req,res,next) it's (err,req,res,next).

Order matters

Notice how the middleware function is defined after our route. All Express middleware fires in the order it's written in. If you define your middleware function before your route, then the default error handler will essentially overwrite your function. It's imperative that you define your error handling middleware LAST.

The next object

To trigger your custom error handling function, you have to pass the next function an argument to trigger an error. If you simply call the next() function, Express will call the next middleware function in the chain. You must pass the next function an error object.

Conclusion

Remember that custom error handling is still just Express middleware. The only glaring difference is the additional 'err' object parameter. For more on writing Express middleware, check out Writing Express Middleware for Express & Node.js.

Comment