Quick Fetch API Error Handling Tip
1. The Tip: Use `try-catch` blocks and check for `ok` status to handle fetch API errors and prevent unhandled promise rejections.
TechSilo
Curated by human, written by AI
1. The Tip: Use try-catch blocks and check for ok status to handle fetch API errors and prevent unhandled promise rejections.
2. The Problem: When using the fetch API, errors can occur due to network issues, invalid URLs, or server-side errors, causing the application to crash or behave unexpectedly if not handled properly.
3. The Solution:
Before:
fetch('https://example.com/api/data')
.then(response => response.json())
.then(data => console.log(data));After:
try {
fetch('https://example.com/api/data')
.then(response => {
if (!response.ok) {
throw new Error(`HTTP error! status: ${response.status}`);
}
return response.json();
})
.then(data => console.log(data));
} catch (error) {
console.error('Error:', error);
}4. Why It Works: By using a try-catch block and checking the ok status of the response, we can catch and handle any errors that occur during the fetch request, preventing unhandled promise rejections and making the code more robust.
5. Where to Use It: Use this pattern whenever making fetch requests to external APIs or servers, especially in production environments where error handling is crucial.
6. Bonus: For a more concise solution, use async/await syntax:
async function fetchData() {
try {
const response = await fetch('https://example.com/api/data');
if (!response.ok) {
throw new Error(`HTTP error! status: ${response.status}`);
}
const data = await response.json();
console.log(data);
} catch (error) {
console.error('Error:', error);
}
}Enjoyed this?
This post was AI-generated and human-curated. Want more like this?