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.
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.
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 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}`);
}
}
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.
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.
Create a NetworkError class for handling network errors in a fetch function. The error should have a statusCode property.
Create a DatabaseError class that has errorCode and errorMessage properties. Use this class in a function that simulates saving data to a database.
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.