Hey i perform a mistake in my url to try the error handling features, but it returns the data value.
// App.js
export default function App() {
const url =
"https://data.grandpoitiers.fr/api/records/1.0/search/?dataset=mobilites-sdtationnement-des-parkings-en-temps-reel&facet=Places_restantes"
const { data, error } = useSWR(url, fetch)
if (error) return <div>error</div>
if (!data) return <div>loding</div>
return (
<div className="App">
<ul>
{data &&
data.records.map(({ fields, recordid }) => (
<li key={`${recordid}`}>
{fields.nom} - {fields.places_restantes}
</li>
))}
</ul>
</div>
)
}
// fetch.js
import fetch from "isomorphic-unfetch"
export default async function(...args) {
const res = await fetch(...args)
return res.json()
}
What can i do to handle my error ?
Fetch by default will not throw an error for 4xx status codes, if the error is in the URL you are probably receiving a 404, what you should do is to check if res.ok or if res.status is between 400 and 499 is false which means you got a 4xx status code and then throw an error, this is what I usually do:
if (response.status >= 400 && response.status <= 499) {
throw new Error('API Client Error', await response.json());
}
This way I get a real error when getting a 4xx and I can use the error of SWR for that.
Most helpful comment
Fetch by default will not throw an error for 4xx status codes, if the error is in the URL you are probably receiving a 404, what you should do is to check if res.ok or if res.status is between 400 and 499 is false which means you got a 4xx status code and then throw an error, this is what I usually do:
This way I get a real error when getting a 4xx and I can use the error of SWR for that.