Throwing a Standard Error

Create an instance of the Error object, passing a short description of the problem to the constructor, which is used for the message property.

function strictDivision(number, divisor) {
    if (divisor == 0) {
        throw new Error('Dividing by zero is not allowed');
    }
    else {
        return number/divisor;
    }
}
// Catch the error
try {
    const result = strictDivision(42, 0);
}
catch (error) {
    // Shows the custom error message
    console.log(`Error: ${error.message}`);
}

function calculateValue(num) {
    if (typeof num !== 'number') {
        throw new TypeError(`Value [${num}] is not a number.`);
    }
}

Throwing a Custom Error

Create a class that inherits from the standard Error class. The constructor should accept the descriptive text for the message property, and use super() to call the base Error class constructor with the message.

class CustomError extends Error {
    constructor(message) {
        super(message);
        this.name = 'CustomError';
        // Optional improvement: clean up the stack trace, if supported
        if (Error.captureStackTrace) {
            Error.captureStackTrace(this, CustomError);
        }
    }
}
// Try raising this error
throw new CustomError('An application-specific problem occurred');

You can also add custom properties to pass extra information about the error condition. Here’s an example that stores a productID after a failed lookup:

class ProductNotFound extends Error {
    constructor(missingProductID) {
        super(`Product ${missingProductID} does not exist in the catalog`);
        this.name = 'ProductNotFound';
        this.productID = missingProductID;

        if (Error.captureStackTrace) {
            Error.captureStackTrace(this, ProductNotFound);
        }
    }
}
try {
    throw new ProductNotFound(420);
}
catch (error) {
    console.log(`An error occured with the message: ${error.message}`);
    if (error instanceof ProductNotFound) {
        console.log(`Missing: ${error.productID}`);
    }
}