Handling errors in TypeScript is crucial for writing robust and reliable applications. TypeScript provides several mechanisms for error handling. Here are some common ways to handle errors in TypeScript:
Using try-catch blocks: TypeScript supports the standard try-catch blocks for handling exceptions. This is useful when you want to catch and handle specific types of errors.
typescripttry {
// Code that may throw an error
} catch (error) {
// Handle the error
console.error(error);
}
Throwing custom errors:
You can create custom error classes by extending the built-in Error
class. This allows you to throw and catch specific types of errors.
typescriptclass CustomError extends Error {
constructor(message: string) {
super(message);
this.name = 'CustomError';
}
}
try {
throw new CustomError('This is a custom error');
} catch (error) {
if (error instanceof CustomError) {
// Handle the custom error
console.error(error.message);
} else {
// Handle other types of errors
console.error(error);
}
}
Using the try-catch-finally
statement:
You can also use the finally
block to execute code regardless of whether an exception is thrown or not.
typescripttry {
// Code that may throw an error
} catch (error) {
// Handle the error
console.error(error);
} finally {
// Code that will always execute
}
Async/Await Error Handling:
When working with asynchronous code, you can use try-catch
blocks with async/await
.
typescriptasync function fetchData() {
try {
const result = await fetch('https://api.example.com/data');
const data = await result.json();
console.log(data);
} catch (error) {
console.error('Error fetching data:', error);
}
}
fetchData();
Using Optional Chaining and Nullish Coalescing:
TypeScript 3.7 introduced optional chaining (?.
) and nullish coalescing (??
) operators, which can be used to handle undefined or null values more gracefully.
typescriptconst value = someObject?.nestedObject?.property ?? 'default';
Validation and Guards: Validate inputs and use type guards to ensure the correctness of your data, reducing the likelihood of runtime errors.
typescriptfunction divide(a: number, b: number): number {
if (b === 0) {
throw new Error('Cannot divide by zero');
}
return a / b;
}
These approaches provide a foundation for handling errors in TypeScript, and the choice between them depends on the specific needs and context of your application.