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?
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?
Share Improve this question asked May 29, 2017 at 7:13 UlyssesUlysses 6,03510 gold badges55 silver badges93 bronze badges 5-
JSON.stringify(x()).includes('error')
?? – Jaydip Jadhav Commented May 29, 2017 at 7:15 -
2
x instanceof Error
– Sirko 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 – Ulysses Commented May 29, 2017 at 7:17
- "".include() returns true false as per the condition. you could use this in if block – Jaydip Jadhav Commented May 29, 2017 at 7:19
- @JaydipJ: Could you please elaborate – Ulysses Commented May 29, 2017 at 7:23
2 Answers
Reset to default 9You 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
}
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 name
try {
throw new Error('Whoops!');
} catch (e) {
console.log(e.name + ': ' + e.message);
}