
Design comparison
SolutionDesign
Community feedback
- @mohamed-fmPosted 3 months ago
This is a well-structured JavaScript code you have, but incorporating error handling can enhance best practices. Here’s an improved version:
try { const response = await fetch('APIURL'); if (response.ok) { console.log('Promise resolved, and the HTTP status is successful.'); // ...handle the response data here } else { // Custom messages for specific HTTP error codes if (response.status === 404) throw new Error('404: Not Found'); if (response.status === 500) throw new Error('500: Internal Server Error'); // For any other server error, throw a general error throw new Error(`Error: ${response.status}`); } } catch (error) { console.error('Fetch error:', error); // Output example: "Fetch error: 404: Not Found" }
This version maintains clarity and effectively handles potential errors when making a fetch request.
Marked as helpful0
Please log in to post a comment
Log in with GitHubJoin our Discord community
Join thousands of Frontend Mentor community members taking the challenges, sharing resources, helping each other, and chatting about all things front-end!
Join our Discord