有没有一种方法在es6inheritance自错误,并没有堆栈跟踪中的构造函数?
我试图通过扩展Error来编写一个HTTPError
类:
class HTTPError extends Error { constructor(codeArg, message){ let code = codeArg || 500; super(message || http.STATUS_CODES[code]); // first line in stack trace this.code = code; } }
这大部分工作正常,但是当我throw
这样的错误时, super
被调用的行是堆栈跟踪中的第一行(假设nodejs):
> const HTTPError = require('./HTTPError') undefined > let e = new HTTPError(418) undefined > throw e Error: I'm a teapot at HTTPError (/home/pat/Scripts/js/HTTPError.js:6:6) at repl:1:9 at sigintHandlersWrap (vm.js:32:31) at sigintHandlersWrap (vm.js:96:12) at ContextifyScript.Script.runInContext (vm.js:31:12) at REPLServer.defaultEval (repl.js:308:29) at bound (domain.js:280:14) at REPLServer.runBound [as eval] (domain.js:293:12) at REPLServer.<anonymous> (repl.js:489:10) at emitOne (events.js:101:20) > e.code 418
堆栈跟踪的第一行在HTTPError
的构造函数中。 有趣的一个(它创build的那个)是第二个repl:1:9
行。 有没有解决的办法?
Error.captureStackTrace
应该能够解决这个问题,虽然它不是标准的ES6。
class HTTPError extends Error { constructor(codeArg, message){ let code = codeArg || 500; super(message || http.STATUS_CODES[code]); Error.captureStackTrace(this, new.target); this.code = code; } }
最终我会在Error
构造函数中调用它,但这不应该是必要的。 还没有标准的堆栈跟踪,所以这是完全依赖于实现的行为。
我认为唯一的办法是手动从堆栈中删除该行。
class HTTPError extends Error { constructor(codeArg, message){ let code = codeArg || 500; super(message || http.STATUS_CODES[code]); // first line in stack trace this.code = code; const stack = this.stack.split('\n') stack.splice(1, 1) this.stack = stack.join('\n') } }