如何在NodeJS中为自定义错误类获取正确的回溯?

我对于在JavaScript中创build自定义Error类的“正确”方式的理解如下所示:

function MyError(message) { this.name = "MyError"; this.message = message || "Default Message"; } MyError.prototype = new Error(); MyError.prototype.constructor = MyError; 

(代码片段从https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Error中唤醒。)

使用NodeJS,如果我尝试检查这种types的错误,如:

 var err = new MyError("whoops"); assert.ifError(err); 

…回溯将显示我在编译时创build的Error对象的上下文,作为MyError的原型,而不是我用“new MyError()”创build的MyError对象。

有什么方法可以得到正确的回溯数据,而不是原型?

我们需要调用超级函数 – captureStackTrace

 var util = require('util'); function MyError(message) { Error.call(this); //super constructor Error.captureStackTrace(this, this.constructor); //super helper method to include stack trace in error object this.name = this.constructor.name; //set our function's name as error name. this.message = message; //set the error message } // inherit from Error util.inherits(MyError, Error); 

更新:

您可以使用此节点模块轻松扩展错误typeshttps://github.com/jayyvis/extend-error

@Jay Kumar,在这里有一个很好的答案。 但是,也许这里是另一个类似的解决scheme

 module.exports = function CustomError(message, extra) { Error.captureStackTrace(this, this.constructor); this.name = this.constructor.name; this.message = message; this.extra = extra; }; require('util').inherits(module.exports, Error); 

Error.call(this) – 创build另一个错误对象(浪费了一堆时间)并且根本不触及它

由于ECMAScript6可以在最新的Node.js版本中得到支持。 ES6下的答案可以参考这个链接 。

 class MyError extends Error { constructor(message) { super(message); this.message = message; this.name = 'MyError'; } } 

以下是Node v4.2.1下的testing代码

 class MyError extends Error{ constructor(msg, extra) { super(msg); this.message = msg; this.name = 'MyError'; this.extra = extra; } }; var myerr = new MyError("test", 13); console.log(myerr.stack); console.log(myerr); 

输出:

 MyError: test at MyError (/home/bsadmin/test/test.js:5:8) at Object.<anonymous> (/home/bsadmin/test/test.js:12:13) at Module._compile (module.js:435:26) at Object.Module._extensions..js (module.js:442:10) at Module.load (module.js:356:32) at Function.Module._load (module.js:311:12) at Function.Module.runMain (module.js:467:10) at startup (node.js:134:18) at node.js:961:3 { [MyError: test] name: 'MyError', extra: 13 }