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

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

问题描述

我正在尝试使用在控制台中打印的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'); 

输出未捕获错误:Loremfooipsum dolor

我的期望:未捕获的CustomError:Loremfooipsum dolor

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

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

推荐答案

您使用的是打字稿版本2.1,并转换为ES5吗?请查看重大更改页面的此部分,以了解可能的问题和解决方法: https://github.com/Microsoft/TypeScript-wiki/blob/master/Breaking-Changes.md#extending-built -ins-like-error-array-and-map-may-no-more-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

相关位:


作为建议,您可以在任何超级(...)电话后立即手动调整原型。

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.

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

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