English 中文(简体)
ExpressJS - Error handling
  • 时间:2024-11-03

ExpressJS - Error Handpng


Previous Page Next Page  

Error handpng in Express is done using middleware. But this middleware has special properties. The error handpng middleware are defined in the same way as other middleware functions, except that error-handpng functions MUST have four arguments instead of three – err, req, res, next. For example, to send a response on any error, we can use −

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

Till now we were handpng errors in the routes itself. The error handpng middleware allows us to separate our error logic and send responses accordingly. The next() method we discussed in middleware takes us to next middleware/route handler.

For error handpng, we have the next(err) function. A call to this function skips all middleware and matches us to the next error handler for that route. Let us understand this through an example.

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 handpng middleware
app.use(function(err, req, res, next) {
   res.status(500);
   res.send("Oops, something went wrong.")
});

app.psten(3000);

This error handpng middleware can be strategically placed after routes or contain conditions to detect error types and respond to the cpents accordingly. The above program will display the following output.

Error handpng Advertisements