Error Handling in TypeScript
This article explains error handling in TypeScript.
YouTube Video
Error Handling in TypeScript
Error handling in TypeScript is fundamentally done using the try...catch
construct, just like in JavaScript. In TypeScript, it is possible to more clearly manage error content through type inference. This allows for more precise and readable error handling.
try...catch
Syntax
The basic syntax for error handling is as follows:.
1try {
2 // Code that may throw an error
3 throw new Error("Something went wrong!");
4} catch (error) {
5 // Catch and handle the error
6 console.error("Error:", error);
7} finally {
8 // Code that runs regardless of whether an error occurred
9 console.log("Finally block executed.");
10}
Type-Safe Error Handling
In TypeScript, errors caught within a catch
block are treated as the any
type, but it is recommended to specify the appropriate type for safer error handling. For example, you can define and use a custom error type as follows:.
1class CustomError extends Error {
2 constructor(message: string, public errorCode: number) {
3 super(message);
4 this.name = "CustomError";
5 }
6}
7
8try {
9 throw new CustomError("Invalid operation", 400);
10} catch (error) {
11 if (error instanceof CustomError) {
12 console.error(`Error: ${error.message}, Code: ${error.errorCode}`);
13 } else {
14 console.error("Unknown error occurred");
15 }
16}
In this example, a class called CustomError
is created, and an error is thrown with custom properties such as errorCode
. In the catch
block, use instanceof
to determine the type of error and perform appropriate handling.
Asynchronous Error Handling
In TypeScript, try...catch
is also used to handle errors when using asynchronous functions.
1async function fetchData() {
2 try {
3 const response = await fetch("https://api.example.com/data");
4 if (!response.ok) {
5 throw new Error(`HTTP error! status: ${response.status}`);
6 }
7 const data = await response.json();
8 console.log(data);
9 } catch (error) {
10 console.error("Failed to fetch data:", error);
11 }
12}
13
14fetchData();
In this example, data is fetched using fetch
, and response.ok
is checked to throw an error if the status code is not OK. The error is caught in catch
, and the appropriate log is output.
Summary
In TypeScript, using types to clarify error content makes error handling safer and more readable. When handling errors, it is important to clarify what types of errors might occur and handle them accordingly.
Error
The Error
class in TypeScript extends the Error
class in JavaScript and is a basic object for representing errors. By using the Error
class, you can create an object that includes an error message and perform error handling.
Basics of the Error
Class
The Error
class is used as follows.
1const error = new Error("Something went wrong!");
2console.log(error.message); // "Something went wrong!"
3console.log(error.name); // "Error"
Properties
The Error
class has the following properties:.
- message A string that represents the error message.
- name
The name of the error. By default, it is
"Error"
, but it can be changed by creating a custom error class. - stack Stack trace information used for debugging. A string indicating which code caused the error when it occurred.
Custom Error Class
It is also possible to extend the Error
class and create your own error classes. This is useful in situations where specific error handling is required. For example, it is effective when you want to handle different types of errors such as HTTP request errors or database errors.
Example of Creating a Custom Error
1class CustomError extends Error {
2 constructor(message: string, public errorCode: number) {
3 super(message); // Call the constructor of the parent class 'Error'
4 this.name = "CustomError"; // Set the name of the error
5 }
6}
7
8const customError = new CustomError("Invalid operation", 400);
9console.log(customError.message); // "Invalid operation"
10console.log(customError.name); // "CustomError"
11console.log(customError.errorCode); // 400
- By creating a
CustomError
class and adding information such as error codes, you can manage more comprehensive information about errors.
Inheritance of the Error
Class
In TypeScript, when creating a custom error class by extending the Error
class, there are a few points to be cautious about.
-
Calling
super()
In the constructor of a custom error class, you must callsuper()
to invoke the constructor of theError
class. This ensures thatmessage
andstack
properties are correctly initialized. -
Adding Properties If you want to add extra information to the error object, define new properties within the class. For example, in the above
CustomError
, anerrorCode
property is added.
Throwing and Catching Errors
You can handle errors by throwing errors using the Error
class or a custom error class and then catching them.
1function riskyOperation() {
2 throw new Error("Something went wrong during the operation");
3}
4
5try {
6 riskyOperation();
7} catch (error) {
8 if (error instanceof Error) {
9 console.error(error.message); // "Something went wrong during the operation"
10 console.error(error.name); // "Error"
11 }
12}
In the case of custom errors as well, use instanceof
to identify specific errors and handle them appropriately.
1class CustomError extends Error {
2 constructor(message: string, public errorCode: number) {
3 super(message);
4 this.name = "CustomError";
5 }
6}
7
8try {
9 throw new CustomError("Database connection failed", 500);
10} catch (error) {
11 if (error instanceof CustomError) {
12 console.error(`Error: ${error.message}, Code: ${error.errorCode}`);
13 }
14}
Summary
The Error
class in TypeScript is a fundamental class for performing standard error handling. Furthermore, by extending the Error
class to create custom errors, flexible error handling based on error types and additional information becomes possible.
You can follow along with the above article using Visual Studio Code on our YouTube channel. Please also check out the YouTube channel.