A custom error class gives domain failures a clear name and extra data.

Custom Error Classes

custom.ts
class ValidationError extends Error {
    field: string;

    constructor(field: string, message: string) {
        super(message);
        this.field = field;
    }
}

function requireName(name: string): string {
    if (name.length === 0) {
        throw new ValidationError("name", "required");
    }
    return name.toUpperCase();
}

const inputName: string = ;

try {
    const normalized: string = requireName(inputName);
    console.log(`name=${normalized}`);
} catch (error) {
    if (error instanceof ValidationError) {
        console.log(`${error.field}=invalid`);
    }
}
class ValidationError extends Error {
    field: string;

    constructor(field: string, message: string) {
        super(message);
        this.field = field;
    }
}

function requireName(name: string): string {
    if (name.length === 0) {
        throw new ValidationError("name", "required");
    }
    return name.toUpperCase();
}

const inputName: string = ;

try {
    const normalized: string = requireName(inputName);
    console.log(`name=${normalized}`);
} catch (error) {
    if (error instanceof ValidationError) {
        console.log(`${error.field}=invalid`);
    }
}
class ValidationError extends Error {
    field: string;

    constructor(field: string, message: string) {
        super(message);
        this.field = field;
    }
}

function requireName(name: string): string {
    if (name.length === 0) {
        throw new ValidationError("name", "required");
    }
    return name.toUpperCase();
}

const inputName: string = ;

try {
    const normalized: string = requireName(inputName);
    console.log(`name=${normalized}`);
} catch (error) {
    if (error instanceof ValidationError) {
        console.log(`${error.field}=invalid`);
    }
}
custom error A custom error class extends `Error` and can carry fields that make recovery easier.