When using fetch in JavaScript, it doesn't automatically throw an error for non-2xx status codes (like 404 or 500). You need to manually check if the response is successful by using response.ok and handle the error yourself.
For example, in the code below, we check if the response is okay and throw an error if it's not:
const fetchUsers = async () => {
try {
const response = await fetch('https://api.github.com/usersz'); // Notice the incorrect URL
const data = await response.json();
if (!response.ok) {
console.log('data.message', data.message);
throw new Error(`Error: ${data.message}`);
}
setUsers(data);
console.log(data);
} catch (error) {
console.error(error);
}
};
In contrast, Axios automatically rejects the promise for any HTTP status code outside the 2xx range, making error handling simpler:
axios.get('https://api.github.com/usersz')
.then(response => setUsers(response.data))
.catch(error => console.error(error));
Key Takeaway: With fetch, you must manually check response.ok for non-2xx statuses, whereas Axios handles this for you automatically.
Top comments (0)