Jar Y
Jar Y

Reputation: 13

How to access custom error object thrown by npm module [Error: [object Object]]

An npm module generates an error of this format.

throw new Error(error.data.errors)

where error.data.errors is

{ email: [ 'is invalid' ] }

When I try to access it in the catch block of my code, it comes up as

[Error: [object Object]]

How can I access the original error / error message from my catch block?

Upvotes: 1

Views: 2183

Answers (1)

Steve Kinney
Steve Kinney

Reputation: 776

I just did some experimentation and there doesn't seem to be a lot you can do in this case. It looks like JavaScript calls .toString() on the error message when it's thrown. By default, this is "[object Object]" on all objects.

As far as I can tell, the fix would be to open a pull request that changed the throwing of the error to the following:

throw new Error(JSON.stringify(error.data.errors));

With this change, you could parse the JSON upon catching the error.

try {
  // Whatever functionality causes the error.
} catch (e) {
  var errors = JSON.parse(e.message);
}

Upvotes: 3

Related Questions