TypeScript中的自定义错误类

时间:2015-07-25 11:59:23

标签: inheritance error-handling typescript

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

如何在TypeScript中扩展核心Error类?我已经在SO中找到了帖子:How do I extend a host object (e.g. Error) in TypeScript但是这个解决方案并不适合我。我使用TypeScript 1.5.3

有什么想法吗?

5 个答案:

答案 0 :(得分:80)

TypeScript 2.1在扩展内置插件方面有重大变化,例如Error。

来自TypeScript breaking changes documentation

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

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

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

然后你可以使用:

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

答案 1 :(得分:13)

直到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
);

答案 2 :(得分:13)

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

<强> UnexpectedInput.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);

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

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

答案 3 :(得分:8)

对于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;
  }
}

有一些other alternatives和一个discussion of the reasons

答案 4 :(得分:2)

https://www.npmjs.com/package/ts-custom-error

上有一个很好的库

ts-custom-error可让您轻松创建错误自定义错误:

import { CustomError } from 'ts-custom-error'
 
class HttpError extends CustomError {
    public constructor(
        public code: number,
        message?: string,
    ) {
        super(message)
    }
}

用法:

new HttpError(404, 'Not found')