【问题标题】:How do I extend the Error class?如何扩展 Error 类?
【发布时间】:2016-05-17 15:14:54
【问题描述】:

这是我的代码:

  let errorBadRequest = new Error("Bad request");

  res.statusCode = 400;
  errorBadRequest.errors = err.details.reduce(function(prev, current) {
    prev[current.path] = current.message;
    return prev;
  }, {});
  throw errorBadRequest;

我想在错误实例中扩展 error 属性,但 tsc 说 joi-utils.ts(21,23): error TS2339: Property 'errors' does not exist on type 'Error'.

errors的结构是{fieldname: fieldmsg},根据我的joi request schema来决定。

如何解决打字稿编译器的错误?我想我需要声明一个接口并指定属性。

【问题讨论】:

    标签: node.js interface typescript joi


    【解决方案1】:

    类型“错误”上不存在属性“错误”。

    创建一个名为error-extension.d.ts 的文件并具有以下内容:

    interface Error {
        errors: Error;
    } 
    

    更多:https://basarat.gitbooks.io/typescript/content/docs/types/lib.d.ts.html

    【讨论】:

      【解决方案2】:

      我发现在初始化 Error 类时,实际上它在 Error 中没有 errors 。它应该创建一个接口并将errors 设置为选项。

      这是我的解决方案:

      interface IJoiErrorException extends NodeJS.ErrnoException {
        errors?: Object;
      }
      
      const errorBadRequest: IJoiErrorException = new Error("Bad request");
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2020-06-22
        • 2013-03-30
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多