codingstuff.io
ExploreTutorialsProblemsCS Subjects
Get Started
ExploreTutorialsProblemsCS Subjects
Get Started
codingstuff.io

Master the art of building software through interactive tutorials, real-world problems, and guided projects.

Pune, Maharashtra, India

codingstuffmail@gmail.com

Product

  • Explore
  • Tutorials
  • Problems
  • CS Subjects

Company

  • About
  • Contact
  • Privacy Policy
  • Terms & Conditions
  • Sitemap

© 2026 codingstuff.io. All rights reserved.

Built with ❤️ for developers everywhere

/
/
All Tutorials
🔷

TypeScript

44 / 60 topics
42Error Handling in TypeScript43Try/Catch44Custom Errors
Tutorials/TypeScript/Custom Errors
🔷TypeScript

Custom Errors

Updated 2026-05-15
10 min read

Custom Errors

Introduction

In TypeScript, like in many other programming languages, errors are a natural part of software development. They help us identify and handle issues that arise during the execution of our code. While JavaScript provides built-in error types such as Error, SyntaxError, TypeError, etc., sometimes you might need to define your own custom error classes to better represent specific error conditions in your application.

Custom errors can make your code more readable, maintainable, and easier to debug by providing more context about the nature of the error. In this tutorial, we'll explore how to create and use custom error classes in TypeScript.

Concept

Creating a custom error class involves extending the built-in Error class provided by JavaScript. By doing so, you can add additional properties or methods specific to your application's needs. Here’s a step-by-step guide on how to define and use custom errors:

  1. Extend the Error Class: Create a new class that extends the Error class.
  2. Add Custom Properties: You can add any number of properties to your custom error class to provide more context about the error.
  3. Throw and Catch Errors: Use these custom errors in your code by throwing them when an error condition occurs and catching them using a try-catch block.

Examples

Step 1: Define a Custom Error Class

Let's define a custom error class called UserNotFoundError. This error will be thrown when a user is not found in the system.

TypeScript
1class UserNotFoundError extends Error {
2constructor(message?: string) {
3 super(message || 'User not found');
4 this.name = 'UserNotFoundError';
5}
6}

In this example, we've created a class UserNotFoundError that extends the built-in Error class. We've also set the name property to 'UserNotFoundError', which is useful for identifying the type of error.

Step 2: Throw the Custom Error

Now, let's see how you can throw this custom error in your code.

TypeScript
1function getUserById(userId: string): User {
2const user = users.find(u => u.id === userId);
3
4if (!user) {
5 throw new UserNotFoundError(`User with ID ${userId} not found`);
6}
7
8return user;
9}

In this function, we're trying to find a user by their ID. If the user is not found, we throw a UserNotFoundError with a message indicating that the user was not found.

Step 3: Catch the Custom Error

Finally, let's see how you can catch and handle this custom error.

TypeScript
1try {
2const user = getUserById('non-existent-id');
3console.log(user);
4} catch (error) {
5if (error instanceof UserNotFoundError) {
6 console.error(error.message); // Output: User with ID non-existent-id not found
7} else {
8 console.error('An unexpected error occurred:', error);
9}
10}

In this example, we're using a try-catch block to handle the UserNotFoundError. If the error is an instance of UserNotFoundError, we log the specific message. Otherwise, we log a generic error message.

Advanced Example: Adding Custom Properties

You can also add custom properties to your error class to provide more context.

TypeScript
1class UserNotFoundError extends Error {
2userId: string;
3
4constructor(userId: string) {
5 super(`User with ID ${userId} not found`);
6 this.name = 'UserNotFoundError';
7 this.userId = userId;
8}
9}

Now, when you throw the UserNotFoundError, you can pass the user ID as an argument.

TypeScript
1function getUserById(userId: string): User {
2const user = users.find(u => u.id === userId);
3
4if (!user) {
5 throw new UserNotFoundError(userId);
6}
7
8return user;
9}

And when catching the error, you can access the custom property.

TypeScript
1try {
2const user = getUserById('non-existent-id');
3console.log(user);
4} catch (error) {
5if (error instanceof UserNotFoundError) {
6 console.error(`User with ID ${error.userId} not found`);
7} else {
8 console.error('An unexpected error occurred:', error);
9}
10}

What's Next?

In the next section, we'll dive into debugging TypeScript code. You'll learn how to use tools like breakpoints, debuggers, and logging techniques to identify and fix issues in your applications.

By mastering custom errors and debugging, you'll be well-equipped to handle a wide range of scenarios that arise during software development.


PreviousTry/CatchNext Debugging TypeScript Code

Recommended Gear

Try/CatchDebugging TypeScript Code