State Management · Junior · Question 67 of 75
Why should an SWR fetcher throw on non-OK HTTP responses?
const fetcher = async (url) => {
const res = await fetch(url);
if (!res.ok) throw new Error("Request failed");
return res.json();
};- ✓Correct answer:
fetchdoesn't reject on 404/500, so without throwing SWR would treat error pages as data - 2SWR requires every fetcher to throw at least once
- 3Throwing makes requests faster
Explanation
A thrown error is exposed as error and enables SWR's retry logic. You can attach status and the response body to the error for the UI.