关于继承:TypeScript中的自定义错误类

Custom error class in TypeScript

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

如何在TypeScript中扩展核心Error类? 我已经在SO中找到帖子:如何在TypeScript中扩展宿主对象(例如Error),但该解决方案对我不起作用。 我使用TypeScript 1.5.3

有任何想法吗?


TypeScript 2.1在扩展扩展(如Error)方面具有重大变化。

从TypeScript重大更改文档

1
2
3
4
5
6
7
8
9
10
11
12
class FooError extends Error {
    constructor(m: string) {
        super(m);

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

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

然后,您可以使用:

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


直到1.6发布,我才开始制作自己的可扩展类。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
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
);


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

UnexpectedInput.ts

1
2
3
4
5
6
7
8
9
10
11
12
13
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 = ( new Error()).stack;
  }

}

export default UnexpectedInput;

我的应用程式

1
2
3
4
5
import UnexpectedInput from"./UnexpectedInput";

...

throw new UnexpectedInput(UnexpectedInput.UNSUPPORTED_TYPE);

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

1
2
3
4
5
6
export declare class Error {
  public message: string;
  public name: string;
  public stack: string;
  constructor(message?: string);
}