@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 }