最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

node.js - NodeJSJavascript: how to detect an error object return value? - Stack Overflow

programmeradmin4浏览0评论

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
Add a ment  | 

2 Answers 2

Reset to default 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
}

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);
}
发布评论

评论列表(0)

  1. 暂无评论