Roger Lipscombe
Roger Lipscombe

Reputation: 91845

Getting the stack trace in a custom error handler in Express?

I'm using a custom error page in Express, as explained here.

But when I do that, I only see the error message. I'd like to get hold of the same information as displayed in the default Express error handler (the stacktrace, etc.), so that I can:

  1. Log it to the console (if I could leave the default in place for this, I'd be happy).
  2. Display it on the error page, but only for localhost.

How do I do this?

Upvotes: 7

Views: 10611

Answers (2)

James
James

Reputation: 736

This is a modified version from @generalhenry's answer. You can access the stack trace in err.stack so you can pass it on your '500' view and do some fancy css styles on it.

app.use(function(err, req, res, next) {
   if (err instanceof NotFound) {
       res.render('errors/404');
   } else {
       res.render('errors/500', {error: err, stack: err.stack});
   }
});

function NotFound() {
   this.name = "NotFound";
   Error.call(this, msg);
   Error.captureStackTrace(this, arguments.callee);
}

// below all route handlers
// If all fails, hit em with the 404
app.all('*', function(req, res){
   throw new NotFound;
});

Upvotes: 11

generalhenry
generalhenry

Reputation: 17319

Just use the error provided to the middleware

  // Handle 500
  app.use(function(error, req, res, next) {
     console.error(error);
     if (ISLOCALHOST()) {
       res.json(error, 500);
     } else {
       res.send('500: Internal Server Error', 500);
     }
  });

Upvotes: 1

Related Questions