我希望在TypeScript中创建自己的错误类,扩展核心Error以提供更好的错误处理和自定义报告。例如,我想创建一个HttpRequestError类,它的url、响应和正文被传递到它的构造函数中,Http请求到http://example.com/的响应失败,状态代码500和消息:出了问题并进行了正确的堆栈跟踪。
如何在TypeScript中扩展核心错误类?我已经在SO:如何在TypeScript中扩展主机对象(例如错误)中找到了帖子,但是这个解决方案对我不起作用。我使用TypeScript 1.5.3
有什么想法吗?
发布于 2017-01-02 15:07:41
TypeScript 2.1在扩展内置程序(如错误)方面发生了重大变化。
class FooError extends Error {
constructor(msg: string) {
super(msg);
// Set the prototype explicitly.
Object.setPrototypeOf(this, FooError.prototype);
}
sayHello() {
return "hello " + this.message;
}
}然后你可以使用:
let error = new FooError("Something really bad went wrong");
if(error instanceof FooError){
console.log(error.sayHello());
}发布于 2015-07-25 15:45:34
在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
);发布于 2016-07-09 14:35:34
我使用的是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);
}https://stackoverflow.com/questions/31626231
复制相似问题