4

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?

5
  • JSON.stringify(x()).includes('error') ?? Commented May 29, 2017 at 7:15
  • 2
    x instanceof Error Commented May 29, 2017 at 7:16
  • @JaydipJ: function x () {let err = new Error(); return err} console.log(JSON.stringify(x()).includes('error')) --> gives false Commented May 29, 2017 at 7:17
  • "".include() returns true false as per the condition. you could use this in if block Commented May 29, 2017 at 7:19
  • @JaydipJ: Could you please elaborate Commented May 29, 2017 at 7:23

2 Answers 2

9

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
}
Sign up to request clarification or add additional context in comments.

2 Comments

Other options are if (Error.prototype.isPrototypeOf(y)) or duck-typing like if (y.stack !== undefined)
@thanks Kiril Rogovoy - that works too but the one in the solution is but more readable
0

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);
}

2 Comments

function x () {let err = new Error("err"); return err} console.log(x().prototype) <-- gives undefined Did you mean this?

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.