TypeScript 中的自定义错误类

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/31626231/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-09 06:43:51  来源:igfitidea点击:

Custom error class in TypeScript

inheritanceerror-handlingtypescript

提问by Kuba T

I'd like to create my own error class in TypeScript, extending core Errorto provide better error handling and customized reporting. For example, I want to create an HttpRequestErrorclass with url, response and body passed into its constructor, which reponds with Http request to http://example.comfailed with status code 500 and message: Something went wrongand proper stack trace.

我想在 TypeScript 中创建自己的错误类,扩展核心Error以提供更好的错误处理和自定义报告。例如,我想创建一个HttpRequestError将 url、响应和正文传递到其构造函数的类,该类响应对http://example.com 的Http 请求失败,状态代码为 500 和消息:出现问题和正确的堆栈跟踪。

How to extend core Error class in TypeScript? I've already found post in SO: How do I extend a host object (e.g. Error) in TypeScriptbut this solution doesn't work for me. I use TypeScript 1.5.3

如何在 TypeScript 中扩展核心 Error 类?我已经在 SO: How do I extend a host object (eg Error) in TypeScript 中找到了帖子,但这个解决方案对我不起作用。我使用打字稿 1.5.3

Any ideas?

有任何想法吗?

采纳答案by thoughtrepo

Until 1.6 rolls around, I've just been making my own extendable classes.

在 1.6 推出之前,我一直在制作自己的可扩展类。

class BaseError {
    constructor () {
        Error.apply(this, arguments);
    }
}

BaseError.prototype = new Error();

class HttpRequestError extends BaseError {
    constructor (public status: number, public message: string) {
        super();    
    }
}

var error = new HttpRequestError(500, 'Server Error');

console.log(
    error,
    // True
    error instanceof HttpRequestError,
    // True
    error instanceof Error
);

回答by ziv

TypeScript 2.1 had a breaking changes regarding Extending built-ins like Error.

TypeScript 2.1 在扩展内置函数(如 Error)方面发生了重大变化。

From the TypeScript breaking changes documentation

来自TypeScript 重大变更文档

class FooError extends Error {
    constructor(m: string) {
        super(m);

        // Set the prototype explicitly.
        Object.setPrototypeOf(this, FooError.prototype);
    }

    sayHello() {
        return "hello " + this.message;
    }
}

Then you can use:

然后你可以使用:

let error = new FooError("msg");
if(error instanceof FooError){
   console.log(error.sayHello();
}

回答by Benny Neugebauer

I am using TypeScript 1.8and this is how I use custom error classes:

我使用的是TypeScript 1.8,这就是我使用自定义错误类的方式:

UnexpectedInput.ts

意外输入.ts

class UnexpectedInput extends Error {

  public static UNSUPPORTED_TYPE: string = "Please provide a 'String', 'Uint8Array' or 'Array'.";

  constructor(public message?: string) {
    super(message);
    this.name = "UnexpectedInput";
    this.stack = (<any> new Error()).stack;
  }

}

export default UnexpectedInput;

MyApp.ts

我的应用程序

import UnexpectedInput from "./UnexpectedInput";

...

throw new UnexpectedInput(UnexpectedInput.UNSUPPORTED_TYPE);

For TypeScript versions older than 1.8, you need to declare Error:

对于 1.8 之前的 TypeScript 版本,您需要声明Error

export declare class Error {
  public message: string;
  public name: string;
  public stack: string;
  constructor(message?: string);
}

回答by Peter

For Typescript 3.7.5 this code provided a custom error class that also captured the correct stack information. Note instanceofdoes not work so I use nameinstead

对于 Typescript 3.7.5,此代码提供了一个自定义错误类,该类也捕获了正确的堆栈信息。注意instanceof不起作用,所以我name改用

// based on https://gunargessner.com/subclassing-exception

// example usage
try {
  throw new DataError('Boom')
} catch(error) {
  console.log(error.name === 'DataError') // true
  console.log(error instanceof DataError) // false
  console.log(error instanceof Error) // true
}

class DataError {
  constructor(message: string) {
    const error = Error(message);

    // set immutable object properties
    Object.defineProperty(error, 'message', {
      get() {
        return message;
      }
    });
    Object.defineProperty(error, 'name', {
      get() {
        return 'DataError';
      }
    });
    // capture where error occured
    Error.captureStackTrace(error, DataError);
    return error;
  }
}

There are some other alternativesand a discussion of the reasons.

还有一些其他的选择原因讨论