我试图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
. 有趣的是(创建它的那个)是第二repl:1:9
行。有没有解决的办法?