Reputation: 6015
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
Reputation: 2866
Try this:
All
Error
instances and instances of non-generic errors inherit fromError.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 messageError.prototype.name
: Error nametry {
throw new Error('Whoops!');
} catch (e) {
console.log(e.name + ': ' + e.message);
}
Upvotes: 0
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