Creating and Using Custom Error Classes

Tutorial 2 of 5

1. Introduction

Goal of the Tutorial

In this tutorial, we aim to enlighten you on how to create and use custom error classes in TypeScript. By creating and using these classes, you can handle errors effectively by categorizing them based on their types.

Learning Outcomes

  • Understand what custom error classes are and why they are used.
  • Learn how to create custom error classes.
  • Understand how to throw and catch custom errors.
  • Learn how to handle different types of errors using custom error classes.

Prerequisites

  • Basic knowledge of TypeScript.
  • A basic understanding of object-oriented programming.
  • Familiarity with error handling in TypeScript.

2. Step-by-Step Guide

Error handling is an important part of any application. It ensures that the user gets meaningful feedback when something goes wrong. In TypeScript, we can define our own error classes to throw specific errors.

Creating a Custom Error Class

To create a custom error class, you extend the built-in Error class.

class CustomError extends Error {
  constructor(message?: string) {
    super(message); // pass the message up to the Error constructor
    this.name = 'CustomError'; // set the error name
  }
}

Here, we define a CustomError class that extends the Error class. We pass the error message to the Error constructor using the super keyword and set the error name to 'CustomError'.

Throwing and Catching Custom Errors

Throwing a custom error is just like throwing a regular error. You use the throw keyword followed by an instance of your error class.

throw new CustomError('This is a custom error');

To catch a custom error, you use a try-catch block. Inside the catch block, you can check the type of the error by comparing the error name or using the instanceof keyword.

try {
  throw new CustomError('This is a custom error');
} catch (e) {
  if (e instanceof CustomError) {
    console.log(`Caught a custom error: ${e.message}`);
  } else {
    console.log(`Caught a general error: ${e.message}`);
  }
}

3. Code Examples

Let’s consider a practical example to understand more precisely.

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

function validateUser(user) {
  if (user.name === '') {
    throw new ValidationError('Name cannot be empty');
  }
  // more validation code...
}

try {
  validateUser({ name: '' });
} catch (e) {
  if (e instanceof ValidationError) {
    console.log(`Invalid user data: ${e.message}`);
  } else {
    console.log(`Unknown error: ${e.message}`);
  }
}

In this example, we define a ValidationError class for user validation errors. We then create a validateUser function that throws a ValidationError if the user's name is empty. In the try-catch block, we catch and handle the ValidationError separately from general errors.

4. Summary

In this tutorial, you have learned about custom error classes in TypeScript. You now know how to create custom error classes, throw and catch custom errors, and handle different types of errors using these classes.

To learn more about error handling in TypeScript, you can refer to the official TypeScript documentation.

5. Practice Exercises

  1. Create a NetworkError class for handling network errors in a fetch function. The error should have a statusCode property.

  2. Create a DatabaseError class that has errorCode and errorMessage properties. Use this class in a function that simulates saving data to a database.

  3. Extend your DatabaseError class to have specific error classes like DuplicateKeyError and RecordNotFoundError. Use these classes in your database function.

Remember to use try-catch blocks to catch and handle these errors separately. The solution to these exercises is left as an exercise for the reader.