In this tutorial, we aim to explore error handling and middleware in Express.js. Express.js is a fast, unopinionated, and minimalist web application framework for Node.js.
By the end of this tutorial, you will:
The prerequisites for this tutorial are a basic understanding of JavaScript and some familiarity with Node.js and Express.js.
Middleware functions are functions that have access to the request object (req
), the response object (res
), and the next middleware function in the application’s request-response cycle. The next middleware function is commonly denoted by a variable named next
.
Middleware functions can perform the following tasks:
In Express, 404 responses are not the result of an error, so the error-handler
middleware will not capture them. To handle a 404 response, add a middleware function at the end of the stack.
Errors that occur in synchronous code inside route handlers and middleware require no extra work. If synchronous code throws an error, then Express will catch and process it.
app.use(function(err, req, res, next) {
console.error(err.stack); // Log error message in our server's console
res.status(500); // Announce that this is a 500 error
res.send('Something broke!'); // Inform client about the error
});
In this example, app.use
is used to setup middleware. We're passing a function that accepts four arguments to app.use
. This function is an error handling middleware. Express identifies it as such and passes errors to it.
app.use(function(req, res, next) {
res.status(404).send('Sorry cant find that!');
});
This middleware function does not have an error in its arguments, Express treats it as a regular middleware. You should ensure this comes after all your other routes because responses are sent in order.
In this tutorial, we have learned about error handling and middleware in Express.js. We've seen how Express uses middleware and how to create error handling middleware.
For further learning, consider exploring more about Express middleware, like built-in middleware, third-party middleware, and writing your own middleware functions.
Tips: Always handle errors and be prepared for the unexpected. Remember, middleware functions that do not handle errors must take only three parameters. Otherwise, they might be mistaken for error handling functions.