Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 248
overflower Avatar asked Mar 09 '23 00:03

overflower


1 Answers

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
}
like image 97
Vibhanshu Avatar answered Mar 23 '23 01:03

Vibhanshu