Error Handling (Live Playground)
Handling errors is crucial to build robust and resilient applications. In this tutorial, we will explore various techniques and best practices for error handling in TypeScript.
Using Try-Catch Blocks
The try-catch
block is a common error handling technique in JavaScript that also works in TypeScript. It allows you to catch exceptions thrown within a block of code.
function divide(a: number, b: number): number {
if (b === 0) {
throw new Error('Division by zero is not allowed');
}
return a / b;
}
try {
const result = divide(10, 0);
console.log(result);
} catch (error) {
console.error('Error occurred:', error.message);
}
Custom Error Classes
Creating custom error classes can help categorize and handle specific errors in a more meaningful way. In TypeScript, you can extend the built-in Error
class to create custom error classes.
class DivisionByZeroError extends Error {
constructor() {
super('Division by zero is not allowed');
this.name = 'DivisionByZeroError';
Object.setPrototypeOf(this, new.target.prototype);
}
}
function divide(a: number, b: number): number {
if (b === 0) {
throw new DivisionByZeroError();
}
return a / b;
}
try {
const result = divide(10, 0);
console.log(result);
} catch (error) {
if (error instanceof DivisionByZeroError) {
console.error('Custom error occurred:', error.message);
} else {
console.error('Unknown error occurred:', error.message);
}
}
Handling Promise Errors
When working with Promises, it's essential to handle errors using .catch()
or try-catch
blocks with async/await
.
async function fetchData(url: string): Promise<string> {
// Fetch data from an API
// ...
}
fetchData('https://example.com/data')
.then(data => {
console.log('Data:', data);
})
.catch(error => {
console.error('Error occurred:', error.message);
});
With async/await
, you can use try-catch
blocks:
async function processData(): Promise<void> {
try {
const data = await fetchData('https://example.com/data');
console.log('Data:', data);
} catch (error) {
console.error('Error occurred:', error.message);
}
}
processData();
Conclusion
In this tutorial, we've explored various techniques for error handling in TypeScript, including try-catch
blocks, custom error classes, and handling promise errors. By properly handling errors, you can make your application more robust and resilient to unexpected situations.