Skip to main content

Error Handling in Express.js

Introduction

Express.js is a popular Node.js web application framework that provides a robust and easy to use set of features to develop web and mobile applications. One of the most important aspects of building any application is how it handles errors. This tutorial will guide you through the basics of error handling in Express.js.

What is Error Handling?

In programming, error handling refers to the process of responding to and recovering from error conditions in programs. It's important to handle errors properly in your application to prevent crashes and provide meaningful error messages to the users.

How Express.js Handles Errors

Express.js provides a built-in error handling mechanism, which ensures that any error that occurs in your application will be handled properly. It does this by providing a special type of middleware function, known as an error-handling middleware function.

Error Handling Middleware

In 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.

Error-handling middleware functions have the same structure as other middleware functions, but they have four arguments instead of three: (err, req, res, next). The err argument is an Error object which can be used to handle the error.

Let's see how to define an error-handling middleware function:

app.use(function (err, req, res, next) {
console.error(err.stack)
res.status(500).send('Something broke!')
})

This middleware function logs the error stack trace to the console and responds to the client with a 500 Internal Server Error status code and a message: 'Something broke!'.

Handling Errors in Routes

You can pass errors to the error-handling middleware function by calling next(err) in your route handlers or other middleware functions. Here's an example:

app.get('/', function (req, res, next) {
fs.readFile('/file-does-not-exist', function (err, data) {
if (err) {
next(err) // Passes the error to the error handler
} else {
res.send(data)
}
})
})

In this example, if an error occurs while reading the file (for example, if the file does not exist), the error is passed to the next middleware function in the stack (which is, in this case, the error-handling middleware function).

Conclusion

Error handling is an important part of any application. In Express.js, you can easily handle errors using error-handling middleware functions. Remember to define your error-handling middleware functions after all other app.use() and routes calls, so they can catch errors from the whole application.

Remember, the goal is to handle errors gracefully and provide useful feedback to your users and your logs. With these techniques in your toolkit, you're well on your way to building robust Express.js applications.