Custom error class in TypeScript

TypeScript 2.1 had a breaking changes regarding Extending built-ins like Error.

From the TypeScript breaking changes documentation

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

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

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

Then you can use:

let error = new FooError("Something really bad went wrong");
if(error instanceof FooError){
   console.log(error.sayHello());
}

Leave a Comment

tech