Master TypeScript From Scratch

Learn TypeScript step by step with practical examples, interactive coding lessons, and real-world projects.

TypeScript Error Handling

Error handling helps applications respond safely when something goes wrong. TypeScript provides compile-time type checking, while JavaScript error-handling mechanisms help manage errors that occur during program execution.

Learning objective: Understand runtime errors, try-catch-finally, throwing errors, the unknown type, custom errors, Promise rejection handling, and API error handling.

1. What Is Error Handling?

Error handling is the process of detecting and responding to problems that occur while a program is running. Without suitable error handling, an unexpected failure can interrupt the normal execution of an application.

For example, a student management application may receive invalid input, fail to load student data from an API, or encounter an unexpected server response. Error handling allows the application to report or manage these situations.

▶️
Execute

The application starts an operation.

⚠️
Detect Error

An operation encounters a problem.

🛡️
Handle Error

Handle the failure or show a suitable message.

Remember: TypeScript catches many type-related mistakes during compilation, but it does not prevent every runtime error. External data and runtime operations still need appropriate validation and error handling.

2. Common Types of Errors

📝
Syntax Errors

Occur when code does not follow the language's syntax rules.

// Missing closing parenthesis
console.log("Hello";
🔍
Type Errors

TypeScript can detect incompatible types during type checking.

let age: number = 25;

// TypeScript reports an error:
age = "Twenty";
⚙️
Runtime Errors

Occur while the program executes.

const student = null;

// Runtime error:
console.log(student.name);
🌐
Network and API Errors

Can happen when a request fails or a service returns an unsuccessful response.

fetch("/api/students")
    .catch((error: Error) => {
        console.log(error.message);
    });

3. try-catch Statement

The try block contains code that may throw an error. The catch block handles an error thrown from the associated try block.

try {
    let result = 10 / 0;

    if (!Number.isFinite(result)) {
        throw new Error("Calculation produced an invalid result");
    }

    console.log(result);
}
catch (error: unknown) {
    if (error instanceof Error) {
        console.log("Error: " + error.message);
    }
}

Expected Output

Error: Calculation produced an invalid result

How It Works

  1. The code inside try starts executing.
  2. The calculation produces Infinity in JavaScript.
  3. The condition detects the non-finite result and throws an Error.
  4. The corresponding catch block handles the error and prints its message.

4. Throwing an Error with throw

The throw statement lets us generate an error when a business rule or validation condition is not satisfied.

function validateAge(age: number): string {
    if (age < 18) {
        throw new Error("Age must be at least 18");
    }

    return "Age is valid";
}

try {
    console.log(validateAge(16));
}
catch (error: unknown) {
    if (error instanceof Error) {
        console.log(error.message);
    }
}

Expected Output

Age must be at least 18
Best practice: Use a descriptive error message. Throw an error when an operation cannot proceed correctly, and handle it at an appropriate level of the application.

5. Using finally

The finally block runs after the associated try-catch processing whether the operation succeeds or throws an error. It is often used for cleanup.

function processStudent(): void {
    try {
        console.log("Processing student data");

        throw new Error("Student record could not be loaded");
    }
    catch (error: unknown) {
        if (error instanceof Error) {
            console.log("Error: " + error.message);
        }
    }
    finally {
        console.log("Student processing finished");
    }
}

processStudent();

Expected Output

Processing student data
Error: Student record could not be loaded
Student processing finished

Common Uses of finally

  • Hide a loading indicator after an operation finishes.
  • Reset UI state after a request.
  • Release resources when the relevant API requires cleanup.

6. Handling Errors with unknown

An error can be thrown as an Error object, a string, or another JavaScript value. TypeScript's unknown type requires us to check the value before using properties such as message.

function processData(): void {
    try {
        throw new Error("Invalid student data");
    }
    catch (error: unknown) {
        if (error instanceof Error) {
            console.log("Error message: " + error.message);
        } else {
            console.log("An unknown error occurred");
        }
    }
}

processData();

Expected Output

Error message: Invalid student data
Why unknown? Using unknown is safer than assuming every caught value is an Error. Check its type before accessing properties.

7. Creating Custom Error Classes

A custom error class can represent a specific kind of application failure. This is helpful when different errors need different handling logic.

class StudentNotFoundError extends Error {
    constructor(studentId: number) {
        super("Student with ID " + studentId + " was not found");

        this.name = "StudentNotFoundError";
    }
}

function getStudent(id: number): string {
    if (id !== 101) {
        throw new StudentNotFoundError(id);
    }

    return "Rahul";
}

try {
    const student = getStudent(105);
    console.log(student);
}
catch (error: unknown) {
    if (error instanceof StudentNotFoundError) {
        console.log("Student Error: " + error.message);
    }
    else if (error instanceof Error) {
        console.log("General Error: " + error.message);
    }
}

Expected Output

Student Error: Student with ID 105 was not found

Where Custom Errors Help

StudentNotFoundError

The requested student record does not exist.

ValidationError

The input fails a business validation rule.

PaymentError

A payment-related operation could not be completed.

8. Error Handling with Promises

A Promise may reject. The rejection can be handled with catch(), or by awaiting the Promise inside a try-catch block.

Method 1: Using catch()

const studentPromise: Promise<string> = Promise.reject(
    new Error("Unable to load student")
);

studentPromise
    .then((student) => {
        console.log(student);
    })
    .catch((error: unknown) => {
        if (error instanceof Error) {
            console.log("Error: " + error.message);
        }
    });

Expected Output

Error: Unable to load student

Method 2: Using async/await

async function loadStudent(): Promise<void> {
    try {
        const student = await Promise.reject(
            new Error("Student request failed")
        );

        console.log(student);
    }
    catch (error: unknown) {
        if (error instanceof Error) {
            console.log("Error: " + error.message);
        }
    }
}

loadStudent();

Expected Output

Error: Student request failed
Remember: A rejected Promise remains rejected unless a subsequent Promise handler recovers from the rejection. Handling an error does not automatically mean that the original operation succeeded.

9. Handling API Errors

The fetch() API rejects for certain network failures, but an HTTP response with a status such as 404 or 500 does not normally reject the fetch Promise by itself. Check response.ok to handle unsuccessful HTTP responses.

interface Student {
    id: number;
    name: string;
}

async function getStudentFromApi(): Promise<void> {
    try {
        const response = await fetch(
            "https://jsonplaceholder.typicode.com/users/1"
        );

        if (!response.ok) {
            throw new Error(
                "HTTP request failed with status " + response.status
            );
        }

        const data: unknown = await response.json();

        if (
            typeof data === "object" &&
            data !== null &&
            "id" in data &&
            "name" in data &&
            typeof data.id === "number" &&
            typeof data.name === "string"
        ) {
            const student: Student = {
                id: data.id,
                name: data.name
            };

            console.log("Student ID: " + student.id);
            console.log("Student Name: " + student.name);
        } else {
            throw new Error("Invalid student data received");
        }
    }
    catch (error: unknown) {
        if (error instanceof Error) {
            console.log("Request Error: " + error.message);
        } else {
            console.log("An unexpected error occurred");
        }
    }
}

getStudentFromApi();

Expected Output

Student ID: 1
Student Name: Leanne Graham
Note: The example depends on network access to the external sample API. The runtime validation checks the required fields shown in this example; production code may need more comprehensive validation of external data.

10. Rethrowing an Error

Sometimes a function needs to log or inspect an error but should not hide the failure. In that case, it can throw the error again so that the calling code can handle it.

function loadStudentRecord(): string {
    try {
        throw new Error("Database request failed");
    }
    catch (error: unknown) {
        console.log("Logging error before passing it upward");

        throw error;
    }
}

try {
    loadStudentRecord();
}
catch (error: unknown) {
    if (error instanceof Error) {
        console.log("Caller handled: " + error.message);
    }
}

Expected Output

Logging error before passing it upward
Caller handled: Database request failed
Important: Avoid swallowing an error silently when the application cannot complete its intended operation.

11. Common Error Handling Mistakes

Ignoring errors

An empty catch block can hide a failure and make debugging difficult.

Assuming every error is Error

Use unknown and narrow the type before reading properties.

Not checking response.ok

An HTTP error response does not automatically reject a fetch Promise.

Exposing sensitive data

Do not display passwords, tokens, private data, or detailed internal server errors to end users.

Losing the original failure

When the caller must know that an operation failed, propagate the error or return an explicit failure result.

Using errors for every condition

Use normal condition checks for expected outcomes and reserve errors for exceptional or unsuccessful situations.

Summary

  • Runtime errors can be managed using try-catch.
  • Use throw to report a failed operation.
  • Use finally for cleanup after the try-catch processing.
  • Use unknown for caught errors and narrow their types before accessing properties.
  • Custom error classes help identify specific application failures.
  • Promise rejections can be handled with catch() or try-catch with await.
  • Check response.ok when handling HTTP responses from fetch().
  • Validate external data and avoid exposing sensitive information in error messages.