TypeScript API Error Handling with custom class
TypeScript Error Handling : Exercise-6 with Solution
Write a TypeScript program that reads data from an external API. Create a custom error class, 'ApiError', to handle errors related to API requests. Use this custom error class to catch and display API error messages.
Sample Solution:
TypeScript Code:
// Custom error class for API errors
class ApiError extends Error {
constructor(message: string) {
super(message);
this.name = 'ApiError';
}
}
// Function to simulate an API request (replace with actual API request)
function fetchExternalApiData(): Promise {
return new Promise((resolve, reject) => {
// Simulate an API error
setTimeout(() => {
reject(new ApiError('Failed to fetch data from the API.'));
}, 1000);
});
}
// Function to fetch data from the API and handle errors
async function fetchDataFromApi(): Promise {
try {
const apiData = await fetchExternalApiData();
console.log(`Data from API: ${apiData}`);
} catch (error) {
if (error instanceof ApiError) {
console.error(`API Error: ${error.message}`);
} else {
console.error(`Unexpected Error: ${error.message}`);
}
}
}
// Execute the API request and handle errors
fetchDataFromApi();
Explanations:
In the exercise above -
- First, we define a custom error class called ApiError that extends the built-in Error class. It takes a custom error message as a parameter and sets the error name.
- The "fetchExternalApiData()" function simulates an API request using a Promise and rejects it with an ApiError containing a custom error message to simulate an API error.
- The "fetchDataFromApi() function fetches data from the API using await and handles errors using a try-catch block. If an ApiError is caught, it displays the custom API error message. Otherwise, it handles other unexpected errors.
Output:
Unexpected Error: Failed to fetch data from the API.
TypeScript Editor:
See the Pen TypeScript by w3resource (@w3resource) on CodePen.
Previous: Custom TypeScript Validation Errors.
Next: TypeScript Database Error Handling with custom class.
What is the difficulty level of this exercise?
Test your Programming skills with w3resource's quiz.
- Weekly Trends and Language Statistics
- Weekly Trends and Language Statistics