TypeScript sequential API requests with error handling
TypeScript Error Handling : Exercise-10 with Solution
Write a TypeScript function that makes multiple API requests in sequence. Handle errors from each request and propagate them to the calling function. Implement logging for all errors.
Sample Solution:
TypeScript Code:
// Custom error class for API errors
class ApiError extends Error {
constructor(message: string) {
super(message);
this.name = 'ApiError';
}
}
// Simulated API request function (replace with actual API calls)
function simulateApiRequest(endpoint: string): Promise {
return new Promise((resolve, reject) => {
// Simulate an API error
setTimeout(() => {
if (Math.random() < 0.5) {
reject(new ApiError(`Error in API request for endpoint: ${endpoint}`));
} else {
resolve(`Response from API for endpoint: ${endpoint}`);
}
}, 1000);
});
}
// Function to make multiple API requests in sequence
async function makeSequentialApiRequests(endpoints: string[]): Promise {
const responses: string[] = [];
for (const endpoint of endpoints) {
try {
const response = await simulateApiRequest(endpoint);
responses.push(response);
} catch (error) {
console.error(`API Error: ${error.message}`);
throw error; // Propagate the error to the calling function
}
}
return responses;
}
// Example usage:
const apiEndpoints = ['/api/endpoint1', '/api/endpoint2', '/api/endpoint3'];
makeSequentialApiRequests(apiEndpoints)
.then((responses) => {
console.log('API Responses:');
responses.forEach((response, index) => {
console.log(`[${index + 1}] ${response}`);
});
})
.catch((error) => {
console.error(`Main Application Error: ${error.message}`);
});
Explanations:
In the exercise above -
- First, define a custom error class called "ApiError" for API-related errors.
- The "simulateApiRequest()" function simulates an API request with a random chance of success or failure.
- The "makeSequentialApiRequests()" function makes multiple API requests in sequence using a for...of loop and awaits each request. If any request fails, it catches the 'ApiError', logs it, and propagates it to the calling function.
- In the example usage, we specify a list of API endpoints and call "makeSequentialApiRequests()" function to make these requests sequentially. The responses are logged if all requests succeed, or the main application handles the first encountered error.
Output:
API Error: Error in API request for endpoint: /api/endpoint1 Main Application Error: Error in API request for endpoint: /api/endpoint1
TypeScript Editor:
See the Pen TypeScript by w3resource (@w3resource) on CodePen.
Previous: TypeScript File Handling with error propagation.
Next: TypeScript Multi-Step workflow with error handling.
What is the difficulty level of this exercise?
Test your Programming skills with w3resource's quiz.
It will be nice if you may share this link in any developer community or anywhere else, from where other developers may find this content. Thanks.
https://w3resource.com/typescript-exercises/typescript-error-handling-exercise-10.php
- Weekly Trends and Language Statistics
- Weekly Trends and Language Statistics