Express js Error Handling
Error Handling in the Express is very simple task. This is done by using a type of middleware called error handling middleware. This is the same middleware you have learnt earlier, except it accepts four arguments.
Syntax of Middleware Error Handling
function(err, req, res, next) {
}
Here, the first argument is the error and the rest are the three that you have learnt before. When your application is in error mode, all regular middleware is ignored. Suppose we have three middleware, first and third are regular middleware and the second is error handling. If no error happens, then the error handling middleware will never execute. And if the error occurs, then express skips over other middleware and takes the error handling middleware in the stack.
Handling error in the middleware is very simple task, just call the next with an argument.
Example
var express = require("express");
var app = express();
app.use(function(err, req, res, next) {
console.error(err);
next(err);
});
If we want to pass some specific error message to an error handler, then instantiate the error class.
Example
var express = require("express");
var app = express();
app.get('/', function(req,res,next){
next(new Error('Something went wrong.');
});