The Error class

When a runtime error takes place, an instance of the Error class is thrown:

throw new Error(); 

We can create custom errors in a couple of different ways. The easiest way to achieve it is by passing a string as an argument to the Error class constructor:

throw new Error("My basic custom error"); 

If we need more customizable and advanced control over custom exceptions, we can use inheritance to achieve it:

export class Exception extends Error { 
 
    public constructor(public message: string) { 
        super(message); 
        // Set the prototype explicitly. 
        Object.setPrototypeOf(this, Exception.prototype); 
    } 
    public sayHello() { 
        return `hello ${this.message}`; 
    } 
} 

In the preceding code snippet, we have declared a class named Exception, which inherits ...

Get Learning TypeScript 2.x - Second Edition now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.