TypeScript Error Handling
Error handling is an important part of ensuring program robustness.
TypeScript provides a powerful type system that helps developers better handle and prevent errors.
This article introduces common error handling patterns and best practices in TypeScript.
Why good error handling is needed
Any program may encounter error situations, such as failed network requests, missing files, or invalid user input.
Good error handling can prevent program crashes, provide friendly error messages, and help developers locate problems.
TypeScript's type system can detect potential issues at compile time, reducing runtime errors.
Concept explanation:There are two main approaches to error handling: exception handling (try-catch) and return-value handling (Result type). The former uses thrown exceptions to represent errors, while the latter uses return values to carry error information.
Custom error types
By extending the Error class to create custom error types, you can carry more error information.
This makes error handling more precise and structured.
Example
// Define the application error class
// Extend the built-in Error class, adding an error code
class
AppError
extends
Error
{
// Error code, used for programmatic error handling
code
:
string
;
// Constructor
constructor
(
message
:
string
,
code
:
string
)
{
super
(
message
)
;
// Call the parent class constructor
this
.
name
=
"AppError"
;
// Set the error name
this
.
code
=
code
;
// Save the error code
}
}
// Safe division function
function
divide
(
a
:
number
,
b
:
number
)
:
number
{
// Check whether the divisor is zero
if
(
b
===
0
)
{
// Throw a custom error
throw
new
AppError
(
"Cannot divide by zero"
,
"DIVIDE_BY_ZERO"
)
;
}
return
a
/
b
;
}
// Use try-catch to catch errors
try
{
var
result
=
divide
(
10
,
0
)
;
}
catch
(
error
)
{
// Check the error type
if
(
error
instanceof
AppError
)
{
console.
log
(
"Application error: "
error.
message
", Code: "
error.
code
)
;
}
else
{
console.
log
(
"Unknown error: "
error
)
;
}
}
Running result:
应用错误: Cannot divide by zero, 代码: DIVIDE_BY_ZERO
Error codes:Adding codes to errors helps programs handle different types of errors more precisely.
Result type avoids exceptions
Another error handling approach is to use the Result type.
It carries error information through return values instead of throwing exceptions. This approach is common in functional programming.
Example
// Define the Result type using a union type
// On success it contains ok: true and a value; on failure it contains ok: false and an error
type Result
<
T
,
E
=
Error
=
|
{
ok:
true
;
value
:
T
}
|
{
ok
:
false
;
error
:
E
}
;
// Division function using the Result type
function
safeDivide
(
a
:
number
,
b
:
number
)
:
Result
<
number
,
string
{// Check whether the divisor is zero
if
(
b
===
0
)
{
// Return an error result
return
{
ok
:
false
,
error
:
"Cannot divide by zero"
}
;
}
// Return a success result
return
{
ok
:
true
,
value
:
a
/
b
}
;
}
// Call the function and handle the result
var
result
=
safeDivide
(
10
,
2
)
;
// Handle based on the result type
if
(
result.
ok
)
{
console.
log
(
"Result: "
result.
value
)
;
}
else
{
console.
log
(
"Error: "
result.
error
)
;
}
Running result:
结果: 5
Advantages:The Result type makes error handling explicit: callers must handle possible errors and cannot ignore them.
Async function error handling
In asynchronous functions, error handling is especially important.
You can use try-catch or the Result type to handle errors in asynchronous operations.
Example
// Define a user interface
interface
User
{
id
:
number
;
name
:
string
;
}
// Simulate an async function that fetches a user
async
function
fetchUser
(
id
:
number
)
:
Promise
<
Result
<
User
,
Error
{
try
{// simulate a network request
var
response
=
await fetch
(
"/api/users/"
id
)
;
var
user
=
await response.
json
(
)
;
// Return a success result
return
{
ok
:
true
,
value
:
user
}
;
}
catch
(
error
)
{
// Return an error result
return
{
ok
:
false
,
error
:
error as Error
}
;
}
}
// Main function
async
function
main
(
)
{
// Call the async function
var
result
=
await fetchUser
(
1
)
;
// Handle the result
if
(
result.
ok
)
{
console.
log
(
"User: "
JSON.
stringify
(
result.
value
)
)
;
}
else
{
console.
log
(
"Error: "
result.
error
.
message
)
;
}
}
// Execute the main function
main
(
)
;
Running result:
用户: {"id":1,"name":"Alice"}
Tip:try-catch in an async function catches any error thrown by an await expression.
General error handling wrapper
You can create a general error handling function to simplify error handling in asynchronous code.
Example
// General error handling wrapper function
// Accepts an async function and returns a Result type
async
function
withErrorHandling
<
T
(
fn:
(
)
=>
Promise
<
T
):
Promise
<
Result
<
T
,
Error
{
try
{// Execute the passed-in async function
var
data
=
await fn
(
)
;
// Return a success result
return
{
ok
:
true
,
value
:
data
}
;
}
catch
(
error
)
{
// Return an error result
return
{
ok
:
false
,
error
:
error as Error
}
;
}
}
// Using the general error handling
// Simulate fetching data
var
result
=
await withErrorHandling
(
async
function
(
)
{
var
response
=
await fetch
(
"/api/data"
)
;
return
response.
json
(
)
;
}
)
;
// Handle based on the result
if
(
result.
ok
)
{
console.
log
(
"Data: "
JSON.
stringify
(
result.
value
)
)
;
}
else
{
console.
error
(
"Error:"
,
result.
error
)
;
}
Best practices:Wrapping general error handling logic reduces code duplication and improves maintainability.
Notes
- **Don't ignore errors:** Don't use empty catch blocks to capture and ignore errors
- **Use clear error types:** Prefer specific error types over the generic Error
- **Error boundaries:** Establish a unified error handling mechanism in the application
- **Don't overuse exceptions:** For predictable errors, prefer return values over throwing exceptions
Note:Choose the error handling approach based on the scenario: use exceptions for program errors and Result for business errors.
Summary
Good error handling is the foundation of building robust applications.
- **Custom errors:** Extend the Error class to add information such as error codes
- **Result type:** Handle errors through return values, avoiding exceptions
- **async/await:** Use try-catch to handle asynchronous errors
- **Error wrapping:** Create general error handling functions
- **Error boundaries:** Establish a unified error handling mechanism
Best practices:Choose the appropriate error handling approach based on the specific scenario, balancing code readability and robustness.