Express js error handling
An example app/guide on error handling is available at https://expressjs.com/en/guide/error-handling.html However should fix your code:
// Require Dependencies
var express = require('express');
var app = express();
// Middleware
app.use(app.router); // you need this line so the .get etc. routes are run and if an error within, then the error is parsed to the next middleware (your error reporter)
app.use(function(err, req, res, next) {
if(!err) return next(); // you also need this line
console.log("error!!!");
res.send("error!!!");
});
// Routes
app.get('/', function(request, response) {
throw "some exception";
response.send('Hello World!');
});
// Listen
app.listen(5000, function() {
console.log("Listening on 5000");
});
A few tips:
1) Your code wasn't working because your error handler middleware was run before your route was reached, so the error handler never had a chance to have the error passed to it. This style is known as continuation passing. Put your error handler last in the middleware stack.
2) You should shut down the server when you have an unhandled error. The best way to do that is to call server.close()
, where server is the result of doing var server = http.createServer(app);
Which means, you should do something like this:
var server = http.createServer(app);
app.use(function(err, req, res, next) {
console.log("error!!!");
res.send("error!!!");
server.close();
});
You should probably also time out the server.close(), in case it can't complete (your app is in an undefined state, after all):
var server = http.createServer(app);
app.use(function(err, req, res, next) {
console.log("error!!!");
res.send("error!!!");
server.close();
setTimeout(function () {
process.exit(1);
}, 3*1000);
});
I made a library that does all this for you, and lets you define custom responses, including specialized error views, static files to serve, etc...:
https://github.com/ericelliott/express-error-handler
I had the same problem and couldn't figure out what was wrong. The thing is if you have the express errorHandler defined then your custom error handler is never being called. If you have the next code, simply remove it:
if ('development' === app.get('env')) {
app.use(express.errorHandler());
}
Worked for me:)