How to Handle Catch Error Types in TypeScript?

In this tutorial, I will explain how to handle catch error types in TypeScript with detailed methods and examples. Recently, while working on a project for a client in New York, I encountered an issue where the error messages in my catch blocks were not being handled properly. This led to a lot of confusion and difficulty in debugging. This tutorial will help you avoid similar issues and improve your error handling in TypeScript.

Catch Error Types in TypeScript

TypeScript enhances JavaScript’s error-handling capabilities by allowing you to catch errors with specific types. This is crucial for writing robust and maintainable code. Properly typed errors help narrow down issues quickly and ensure that your application behaves as expected.

Basic Try-Catch Block in TypeScript

Let’s start with a basic TypeScript try-catch block. In TypeScript, the catch clause variable must be typed as any or unknown to avoid compilation errors:

try {
  // Some code that may throw an error
  throw new Error("Something went wrong!");
} catch (error: unknown) {
  console.error((error as Error).message);
}

In this example, we use unknown as the type for the error variable. We then cast it to Error to access the message property. This ensures type safety and avoids potential runtime errors.

Handle Specific Error Types With Simple Example: Number Division Operation

To help beginners understand this topic better, let’s look at a simple example involving a number division operation. We’ll handle potential errors such as division by zero:

function divideNumbers(numerator: number, denominator: number): number {
  if (denominator === 0) {
    throw new Error('Denominator cannot be zero.');
  }
  return numerator / denominator;
}

try {
  const result = divideNumbers(10, 0); // This will throw an error
  console.log('Result:', result);
} catch (error: unknown) {
  console.error('Error:', (error as Error).message);
}

In this example, we define a function divideNumbers that throws an error if the denominator is zero. In the try block, we attempt to divide 10 by 0, which triggers the error. The catch block then handles the error by printing a meaningful error message.

I executed the above TypeScript code using VS code, and you can see the exact output in the screenshot below:

typescript catch error type

Handle Specific Error Types – Advanced Example

Often, you may need to handle specific types of errors differently. For example, if you’re making HTTP requests using Axios, you might want to handle Axios errors separately:

import axios, { AxiosError } from 'axios';

async function fetchData() {
  try {
    const response = await axios.get('https://api.example.com/data');
    console.log(response.data);
  } catch (error: unknown) {
    if (error instanceof AxiosError) {
      console.error('Axios error:', error.message);
    } else {
      console.error('Unexpected error:', (error as Error).message);
    }
  }
}

fetchData();

In this example, we check if the error is an instance of AxiosError and handle it accordingly. This approach allows you to provide more specific error messages and actions based on the error type.

Create Custom Error Classes

Creating custom error classes can further enhance your error-handling strategy. This is particularly useful for domain-specific errors:

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

function validateUserInput(input: string) {
  if (input.length < 5) {
    throw new ValidationError('Input must be at least 5 characters long.');
  }
}

try {
  validateUserInput('abc');
} catch (error: unknown) {
  if (error instanceof ValidationError) {
    console.error('Validation error:', error.message);
  } else {
    console.error('Unexpected error:', (error as Error).message);
  }
}

Here, we define a ValidationError class and use it to throw specific validation errors. In the catch block, we handle ValidationError separately from other errors, providing clear and actionable error messages.

Conclusion

In this tutorial, I explained how to handle catch error types in TypeScript with two examples. You can greatly improve your application’s error-handling capabilities by using unknown error variables, handling specific error types, and creating custom error classes. This tutorial should help you avoid common pitfalls and make your TypeScript code more resilient.

Let me know in the comment below if you still have any questions.

You may also like: