We now have a youtube channel. Subscribe!

Express.js | Error Handling

Express.js | Error Handling


Hello folks! Welcome back to a new section of our tutorial on ExpressJS. In this tutorial guide, we will be studying about ExpressJS Error Handling.

Error handling in Express is executed using middleware. But this middleware has unique properties. The error handling middleware is defined the same way as other middleware functions, however, error-handling functions Must have four arguments instead of three - err, req, res, next.

Example

To send a response on any error, make use of the following code -

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

Till now we have been handling errors in the routes itself. The error handling middleware lets us to separate our error logic and send responses accordingly. The next() method we talked about in middleware tutorial takes us to next middleware/route handler.

For handling of errors, we have the next(err) function. A call to this function bypasses all middleware and then matches us to the next error handler for that route.

Example

Let us consider the following example for a better understanding -

var express = require('express');
var app = express();

app.get('/', function(req, res){
   //Create an error and pass it to the next function
   var err = new Error("Something went wrong");
   next(err);
});

/*
 * other route handlers and middleware here
 * ....
 */

//An error handling middleware
app.use(function(err, req, res, next) {
   res.status(500);
   res.send("Oops, something went wrong.")
});

app.listen(3000);

This error handling middleware function can be strategically placed after routes or holds conditions to detect error types and respond to the clients accordingly.

Output

The above example will show the following output.

error_handling


Alright guys! This is where we are going to be rounding up for this tutorial. In our next tutorial guide, we are going to be discussing about ExpressJS Debugging.

Feel free to ask your questions where necessary and we will attend to them as soon as possible. If this tutorial was helpful to you, you can use the share button to share this tutorial.

Follow us on our various social media platforms to stay updated with our latest tutorials. You can also subscribe to our newsletter in order to get our tutorials delivered directly to your emails.

Thanks for reading and bye for now.

Post a Comment

Hello dear readers! Please kindly try your best to make sure your comments comply with our comment policy guidelines. You can visit our comment policy page to view these guidelines which are clearly stated. Thank you.
© 2022 ‧ WebDesignTutorialz. All rights reserved. Developed by Jago Desain