1

I have a default error handler setup in my express application as so.

 app.use(function unhandledErrorHandler(err, req, res, next) {
   res.status(err.status || 500).json({
     error: err
   });
 });

However whenever I call a route and an error is thrown I am getting a response that looks like this.

{
  "error": {}
}

Can someone help my understand why express is returning my error as an empty Object?

C Deuter
  • 893
  • 1
  • 8
  • 14
  • 1
    Have you defined that middleware function at the very end of your routes? – Maria Ines Parnisari Jun 07 '17 at 02:19
  • Yep, It is otherwise working exactly as expected. If I change the `{error: err}` to `{error: err.stack}` I get what I am expecting, I am more curious about the mechanisms of the Error Object / express that are causing this. – C Deuter Jun 07 '17 at 02:27

1 Answers1

7

The reason Error instances are being shown as empty objects is because the normal properties (e.g. .message, .stack, etc.) on an Error object are not set as enumerable and JSON.stringify() (used by res.json()) ignores non-enumerable properties.

If you just want to send the message portion (not including the stack trace), you could do this instead:

res.json({ error: err.message });

or

res.json({ error: { message: err.message } });

Otherwise if you want to include other custom, enumerable properties that may have been tacked onto the Error instance, you could make .message enumerable and then use the same code you're using now:

Object.defineProperty(err, 'message', { enumerable: true });
res.json({ error: err });
mscdex
  • 104,356
  • 15
  • 192
  • 153