2017-05-29 7 views
0

私は、何らかのオブジェクトを返すか、カスタムエラーオブジェクトを返す可能性のある関数を持っています。エラーオブジェクトタイプを検出できません。NodeJS/Javascript:エラーオブジェクトの戻り値を検出する方法は?

私はconstructor.match(/ Error/i)を試していますか、プロトタイプのObject.keysで作業しようとしましたが、何も機能しませんでした。以下はコードですか?

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 

どのように出力エラーの種類を検出するのですか?

+0

'JSON.stringify(X())を以下のように返されたオブジェクトがinstanceofエラーであるかどうかをチェックすることができます。'( 'エラー')が含ま?? –

+2

'x instanceof Error' – Sirko

+0

@JaydipJ:function x(){let err = new Error(); console.log(JSON.stringify(x))。includes( 'error')) - > falseを返す – BabyGroot

答えて

4

let y = x(); 
if(y instanceof Error) { 
    // returned object is error 
} else { 
//returned object is not error 
} 
+0

うまくいってくれてありがとう – BabyGroot

+1

その他のオプションは 'if(Error.prototype.isPrototypeOf(y))'または'if(y.stack!== undefined)'のようなダックタイピング –

+0

@thanks Kiril Rogovoy - これも機能しますが、解決策の中のものは読みやすくなりますが – BabyGroot

0

標準プロパティ

Error.prototype.constructor 

は、インスタンスのプロトタイプを作成した関数を指定します。この

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. 

プロパティを試してみてください。

Error.prototype.message 

エラーメッセージ。

Error.prototype.name 

エラー名。

try { 
    throw new Error('Whoops!'); 
} catch (e) { 
    console.log(e.name + ': ' + e.message); 
} 
+0

function x(){let err = new Error( "err"); return err} console.log(x()。prototype)< - 定義されていません これは意味ですか? – BabyGroot

+0

これをチェックしてくださいhttps://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Error –

関連する問題