打字稿 - 扩展错误类 [英] Typescript - Extending Error class

查看:40
本文介绍了打字稿 - 扩展错误类的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图抛出一个自定义错误,在控制台中打印我的CustomError"类名而不是Error",但没有成功:

I'm trying to throw a custom error with my "CustomError" class name printed in the console instead of "Error", with no success:

class CustomError extends Error { 
    constructor(message: string) {
      super(`Lorem "${message}" ipsum dolor.`);
      this.name = 'CustomError';
    }
}
throw new CustomError('foo'); 

输出是未捕获的错误:Lorem "foo" ipsum dolor.

我所期望的:未捕获的自定义错误:Lorem "foo" ipsum dolor.

我想知道是否可以仅使用 TS 来完成(不会弄乱 JS 原型)?

I wonder if that can be done using TS only (without messing with JS prototypes)?

推荐答案

您是否使用 typescript 2.1 版并转译为 ES5?检查中断更改页面的这一部分可能的问题和解决方法:https://github.com/Microsoft/TypeScript-wiki/blob/master/Breaking-Changes.md#extending-built-ins-like-error-array-and-map-may-no-longer-work

Are you using typescript version 2.1, and transpiling to ES5? Check this section of the breaking changes page for possible issues and workaround: https://github.com/Microsoft/TypeScript-wiki/blob/master/Breaking-Changes.md#extending-built-ins-like-error-array-and-map-may-no-longer-work

相关位:

建议您在任何 super(...) 调用后立即手动调整原型.

As a recommendation, you can manually adjust the prototype immediately after any super(...) calls.

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

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

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

然而,FooError 的任何子类也必须手动设置原型.对于不支持 Object.setPrototypeOf 的运行时,您可以改为使用 __proto__.

However, any subclass of FooError will have to manually set the prototype as well. For runtimes that don't support Object.setPrototypeOf, you may instead be able to use __proto__.

遗憾的是,这些变通办法不适用于 Internet Explorer 10 及更早版本.可以手动将方法从原型复制到实例本身(即 FooError.prototype 到此),但原型链本身无法修复.

Unfortunately, these workarounds will not work on Internet Explorer 10 and prior. One can manually copy methods from the prototype onto the instance itself (i.e. FooError.prototype onto this), but the prototype chain itself cannot be fixed.

这篇关于打字稿 - 扩展错误类的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆