16

我对在 JavaScript 中创建自定义 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,如果我尝试检查此类错误,例如:

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

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

有什么方法可以让我获得实际错误的正确回溯数据,而不是原型?

4

2 回答 2

37

我们需要调用超级函数——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);

更新:

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

于 2011-12-10T22:41:54.637 回答
3

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

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) - 创建另一个错误对象(浪费大量时间)并且根本不触及它

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

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

下面是测试代码Node v4.2.1

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 }
于 2015-11-24T10:06:26.240 回答