Managing errors in Express
In the previous chapters, we learned how to create a REST API application using Express and we saw how to handle errors in Express applications, but in this section, we are going to refresh the concepts and extend them.
Error-handling middleware
Express has a built-in error-handling middleware that can be used to handle errors in a centralized way. This middleware is executed when an error occurs in the application. This middleware is executed after all the other middleware and routes have been executed. It is executed only when an error occurs, so it is important to add it at the end of the middleware chain, like so:
import express from 'express' const app = express() // Other middlewares... app.use((err, req, res, next) => { console.error(err.stack) res.status(500).send('Something broke!') }) // Route handler...
Custom errors
If you are building a REST API application, you could add a property...