Ulysses
Ulysses

Reputation: 6015

NodeJS/Javascript: how to detect an error object return value?

I have a function that might return some object or might return a custom error object. I am unable to detect error object type.

I have tried constructor.match(/Error/i) or tried to work on Object.keys of prototype but nothing worked. Following is the code?

function x() {
    try {
        ...
    } catch {e} {
       let err = new Error('caught error')
       return err
    }
    return someObject
}

//the following gives: TypeError: err.constructor.match is not a function
if (x().constructor.match(/Error/i)) {
   //log error
}
//do something

Any ideas how to detect the output error type?

Upvotes: 4

Views: 5881

Answers (2)

Francesco Taioli
Francesco Taioli

Reputation: 2866

Try this:

All Error instances and instances of non-generic errors inherit from Error.prototype. As with all constructor functions, you can use the prototype of the constructor to add properties or methods to all instances created with that constructor.

Standard properties:

  • Error.prototype.constructor: Specifies the function that created an instance's prototype.
  • Error.prototype.message: Error message
  • Error.prototype.name: Error name
try {
  throw new Error('Whoops!');
} catch (e) {
  console.log(e.name + ': ' + e.message);
}

Upvotes: 0

Vibhanshu
Vibhanshu

Reputation: 542

You can check if returned object is an instanceof Error as follows

let y = x();
if(y instanceof Error) {
  // returned object is error
} else {
 //returned object is not error
}

Upvotes: 9

Related Questions