在 es6 中有没有一种方法可以从 Error 继承并且在堆栈跟踪中没有构造函数?

Is there a way in es6 to inherit from Error and not have the constructor in the stacktrace?

我试图通过扩展错误来编写 HTTPError class:

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 。有解决办法吗?

我认为唯一的方法是从堆栈中手动删除该行。

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')
   }
}

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 构造函数中的错误,但这不是必需的。目前还没有堆栈跟踪的标准,所以这完全是依赖于实现的行为。