Inheritance TypeScript中的自定义错误类

Inheritance TypeScript中的自定义错误类,inheritance,error-handling,typescript,Inheritance,Error Handling,Typescript,我想在TypeScript中创建自己的错误类,扩展coreerror,以提供更好的错误处理和定制报告。例如,我想创建一个HttpRequestError类,将url、响应和主体传递到它的构造函数中,该类使用Http请求向failed进行响应,状态代码为500,消息为:发生了错误,堆栈跟踪正确 如何扩展TypeScript中的核心错误类?我已经在SO中找到了帖子:但这个解决方案对我不起作用。我使用TypeScript 1.5.3 有什么想法吗?在1.6版本推出之前,我一直在制作自己的可扩展类 cl

我想在TypeScript中创建自己的错误类,扩展core
error
,以提供更好的错误处理和定制报告。例如,我想创建一个
HttpRequestError
类,将url、响应和主体传递到它的构造函数中,该类使用Http请求向failed进行响应,状态代码为500,消息为:发生了错误,堆栈跟踪正确

如何扩展TypeScript中的核心错误类?我已经在SO中找到了帖子:但这个解决方案对我不起作用。我使用TypeScript 1.5.3


有什么想法吗?

在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
);

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

意外输入。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;
import UnexpectedInput from "./UnexpectedInput";

...

throw new UnexpectedInput(UnexpectedInput.UNSUPPORTED_TYPE);
对于早于1.8的TypeScript版本,您需要声明
错误

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

TypeScript 2.1在扩展内置程序方面有一个突破性的变化,比如错误

然后您可以使用:

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

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

这里有一些和一个。

这里有一个整洁的图书馆

ts自定义错误
允许您非常轻松地创建错误自定义错误:

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

new HttpError(404, 'Not found')

这些答案在哪些方面对你没有帮助?您还不能扩展错误类@DavidSherret我有一些编译错误,正如我所看到的,
tsc
在早期版本中没有报告这些错误。是的,我的解决方案很熟悉,我唯一想知道的是如何以与project相同的方式扩展核心类。遗憾的是,我看不到TS 1.6的发布日期。所以,好吧,我认为你的解决方案到目前为止最接近我的期望,谢谢!)BaseError不能用类语法定义方法,这样它们将被替换为
BaseError.prototype=new Error()
。值得一提的是,在任何
super(…)
调用之后都需要立即调用
对象.setPrototypeOf
。为什么我们需要添加
对象.setPrototypeOf(这是FooError.prototype)?我需要确保
tsconfig.json
的“目标”:“es6”
。如果单击“TypeScript breaking changes documentation”链接,请注意Object.setPrototypeOf@Searene,它解释了原因。使用这种方法时应该小心。我想我读到过调用stack属性是很昂贵的,应该在代码中避免。我认为您可能会为自定义错误增加大量开销。从文档“访问error.stack属性时,表示堆栈跟踪的字符串是延迟生成的。”我不明白为什么首先需要这样做:
this.stack=(new error()).stack应该从错误类继承,是吗?
new HttpError(404, 'Not found')