Error Handling in TypeScript

November 7, 2024

Error Handling in TypeScript

In this lesson, we discuss how to handle errors in TypeScript, including try-catch blocks and custom error classes. Proper error handling is crucial for building robust applications that can gracefully deal with unexpected situations.

Understanding Errors in TypeScript

Errors in TypeScript (and JavaScript) can occur for various reasons, such as:

  • Runtime errors due to invalid operations (e.g., dividing by zero)
  • Logical errors that result in unintended behavior
  • Network errors when making API calls

TypeScript provides a way to handle these errors using try-catch blocks.

Using Try-Catch Blocks

The try-catch statement allows you to test a block of code for errors. If an error occurs, the code in the catch block is executed.

function riskyOperation() {
    // Simulating an error
    throw new Error('Something went wrong!');
}

try {
    riskyOperation();
} catch (error) {
    console.error('Error caught:', error.message);
}

In this example, the riskyOperation function throws an error. The try block attempts to execute this function, and if it fails, the catch block handles the error, logging it to the console.

Finally Block

You can also use a finally block, which will execute after the try and catch blocks, regardless of whether an error was thrown or not. This is useful for cleaning up resources.

try {
    riskyOperation();
} catch (error) {
    console.error('Error caught:', error.message);
} finally {
    console.log('Cleanup actions can be performed here.');
}

Custom Error Classes

Sometimes, you may want to create your own error types. This allows you to throw and catch specific errors more effectively. You can create a custom error class by extending the built-in Error class.

class CustomError extends Error {
    constructor(message: string) {
        super(message);
        this.name = 'CustomError';
    }
}

function anotherRiskyOperation() {
    throw new CustomError('A custom error occurred!');
}

try {
    anotherRiskyOperation();
} catch (error) {
    if (error instanceof CustomError) {
        console.error('Caught a custom error:', error.message);
    } else {
        console.error('Caught a different error:', error);
    }
}

In this example, we create a CustomError class that extends the Error class. When we throw this error in the anotherRiskyOperation function, we can catch it in a specific way, allowing for more precise error handling.

Best Practices for Error Handling

  • Be specific: Use custom error types for different error scenarios.
  • Log errors: Always log errors to help with debugging.
  • Graceful degradation: Ensure your application can continue to function or provide feedback to users even when an error occurs.
  • Use finally for cleanup: Always clean up resources, such as closing files or network connections, in the finally block.

Conclusion

Effective error handling is a vital part of programming in TypeScript. By using try-catch blocks and creating custom error classes, you can manage errors gracefully, leading to a better user experience and more maintainable code.