我已经实现了自己的自定义错误:
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
使用一个可重写的方法来格式化错误对象,但是这个方法是什么呢?
log
函数?你能否澄清一下吗?它如何使console.log(e)
输出正确格式的错误信息? - vitaly-tconsole.log
时,它们会变得丑陋。 - vitaly-tconsole.error()
呢? - Sebas