Stephen Last
Stephen Last

Reputation: 5781

Error objects, native and custom, how to tell the difference?

In my node app I want to work with custom errors as well as native errors. I always seem to struggle with error handling because errors seem to be a special type of object, not a normal JavaScript object.

I'm trying to use errors for custom errors.

What I want to end up with is a JSON string that I can return to the client, for both types of error (custom and native).

I can create a custom error like:

errors.create({
  name: `UnableToDelete`,
  defaultMessage: `Unable to perform delete.`
});
let e1 = new errors.UnableToDelete({
  explanation: `Group has members. You can't delete a group that has members.`
});

I can create a native error like:

let e2 = new Error(`Unable to perform delete.`);

I might also get a native error from somewhere else, like from node, or another third party module, for example if something goes wrong while connecting to a database.

The problem I have is being able to tell the difference between these errors, so I can call the right method on it.

I don't want to have to wrap every error, everywhere in my code, in the correct method. I want to have my Express error handler do that:

function error(err, req, res, next) {
    // use either JSON.stringify() or errors.errorToJSON() on
    // the err object. 
}

How can I tell the difference between a custom and native error, in order to know which method to use..?

Upvotes: 1

Views: 97

Answers (1)

alemures
alemures

Reputation: 116

The nodejs module errors exports a function called isError(err) that will return true if you send a custom error created by the module.

var customError = new errors.HttpError();
var nativeError = new Error();
errors.isError(customError); // Will return true
errors.isError(nativeError); // Will return false

Upvotes: 1

Related Questions