Swr: Error with fetch don't works

Created on 24 Feb 2020  路  1Comment  路  Source: vercel/swr

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 ?

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:

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.

>All comments

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.

Was this page helpful?
0 / 5 - 0 ratings

Related issues

oran1248 picture oran1248  路  3Comments

polc picture polc  路  3Comments

loveholly picture loveholly  路  3Comments

timurmaio picture timurmaio  路  3Comments

dandrei picture dandrei  路  3Comments