自定义错误格式

vit*_*y-t 7 javascript node.js

我已经实现了自己的自定义错误:

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
    }
});
Run Code Online (Sandbox Code Playgroud)

而我所缺少的是让它在屏幕上显示,就像发生常规的无法错误时一样,即如果我们这样做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
Run Code Online (Sandbox Code Playgroud)

现在,当我这样做时,我想要同样格式良好的输出:

try {
    throw new MyError("Ops!");
} catch (e) {
    console.log(e);
}
Run Code Online (Sandbox Code Playgroud)

但相反,我得到:

{ [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!' }
Run Code Online (Sandbox Code Playgroud)

还需要做些什么来使console.log(e)输出MyError自动生成相同格式良好的表示,而不必使用显式e.stack引用?

更新:起初我看到了一些关于toJSON要实现的方法的建议,我做了,但它没有完全奏效.我假设必须有一个可覆盖的方法,console.log用于格式化错误对象,但它是什么呢?

tke*_*ers 4

您不应该重写该toJSON方法(或者,toString如经常假设的那样),而应该重写,该方法在尝试访问V8 中的对象inspect时使用。console.log

例如:

MyError.prototype.inspect = function () {
    return this.stack;
};
Run Code Online (Sandbox Code Playgroud)

也许应该可以解决问题。