@ Джей Кумар, здесь есть один хороший ответ. Однако, может быть, здесь есть другое подобное решение здесь
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 }