Search code examples
javascripttypescript

Typescript - Extending Error class


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

The output is Uncaught Error: Lorem "foo" ipsum dolor.

What I expect: Uncaught CustomError: Lorem "foo" ipsum dolor.

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


Solution

  • 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/94fb0618c7185f86afec26e6b4d2d6eb7c049e47/Breaking-Changes.md#extending-built-ins-like-error-array-and-map-may-no-longer-work

    The relevant bit:

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

    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__.

    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.