ExpressJS Error Handling
ExpressJS provides a simple but powerful error handling mechanism that allows developers to handle all types of errors that may occur during the execution of their application. This page explains how to use this error handling mechanism effectively.
Syntax
The following is the syntax for handling errors in an ExpressJS application:
app.use(function (err, req, res, next) {
// Handle the error
});
Example
app.get('/user/:id', function(req, res, next) {
if (req.params.id !== '123') {
return next(new Error('User not found'));
}
res.sendStatus(200);
});
app.use(function(err, req, res, next) {
res.status(500).send('Error occurred: ' + err.message);
});
Output
If the user requests a URL with an ID that does not exist in the database, the output would be:
Error occurred: User not found
Explanation
In the above example, the app.get()
function is used to handle a GET request to the /user/:id
endpoint. If the ID provided by the user does not exist in the database, the next()
function is called with an error object that is generated using the Error()
constructor function.
The app.use()
function is used to handle all errors that occur in the application, and it takes a callback function with four parameters:
err
: The error object that was passed by thenext()
function.req
: The request object passed by the middleware.res
: The response object passed by the middleware.next
: The next middleware function.
Inside the error handling middleware, the error is sent to the client using the res.status()
and res.send()
functions with a 500 status code.
Use
The error handling middleware should be the last middleware function in the stack. The next()
function should be called with the error object when an error occurs. The error handling middleware should be responsible for sending a response to the client.
Important Points
- The error handling middleware should handle all errors that are not caught by other middleware functions.
- The error handling middleware should be the last middleware function in the stack.
- The
next()
function should be called with the error object when an error occurs in a middleware function.
Summary
In summary, ExpressJS provides a powerful error handling mechanism that allows developers to handle all types of errors that may occur during the execution of their application. The error handling middleware should be the last middleware function in the stack, and it should handle all errors that are not caught by other middleware functions. The next()
function should be called with the error object when an error occurs in a middleware function, and the error handling middleware should be responsible for sending a response to the client.