我实现了自己的自定义错误:
function MyError() {
var temp = Error.apply(this, arguments);
temp.name = this.name = 'MyError';
this.stack = temp.stack;
this.message = temp.message;
}
MyError.prototype = Object.create(Error.prototype, {
constructor: {
value: MyError,
writable: true,
configurable: true
}
});
我缺少的是让它在屏幕上显示自己,就像发生常规未处理错误时那样,即如果我们throw new Error('Hello!')
,我们得到输出:
throw new Error('Hello!');
^
Error: Hello!
at Object.<anonymous> (D:\NodeJS\tests\test1.js:28:7)
at Module._compile (module.js:425:26)
at Object.Module._extensions..js (module.js:432:10)
at Module.load (module.js:356:32)
at Function.Module._load (module.js:313:12)
at Function.Module.runMain (module.js:457:10)
at startup (node.js:138:18)
at node.js:974:3
现在,当我执行此操作时,我想要同样格式良好的输出:
try {
throw new MyError("Ops!");
} catch (e) {
console.log(e);
}
但我得到的是:
{ [MyError: Ops!]
name: 'MyError',
stack: 'MyError: Ops!\n at MyError.Error (native)\n at new MyError (D:\\NodeJS\\tests\\test1.js:2:22)\n at Object.<anonymous> (D:\\NodeJS\\tests\\test1.js:22:11)\n at Module._compile (module.js:425:26)\n at O
bject.Module._extensions..js (module.js:432:10)\n at Module.load (module.js:356:32)\n at Function.Module._load (module.js:313:12)\n at Function.Module.runMain (module.js:457:10)\n at startup (node.js:138:18)\n
at node.js:974:3',
message: 'Ops!' }
还需要做些什么才能使 console.log(e)
自动为 MyError
输出同样格式良好的演示文稿,而不必使用显式的 e .stack
引用?
更新:起初我看到了一些关于要实现的方法 toJSON
的建议,我照做了,但效果并不理想。我假设 console.log
必须使用一个可覆盖的方法来格式化错误对象,但它是什么?
最佳答案
与其重写 toJSON
方法(或经常假设的 toString
),您应该重写 inspect
,它在尝试时使用console.log
V8 中的一个对象。
例如:
MyError.prototype.inspect = function () {
return this.stack;
};
应该可以解决问题。
关于javascript - 自定义错误格式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33791417/