Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

How to read 400 - Bad Request JSON response with useAsync onReject ? #232

Open
ghost opened this issue Dec 4, 2019 · 1 comment
Open

Comments

@ghost
Copy link

ghost commented Dec 4, 2019

Hello,

I'm struggling to get the error JSON response from a useAsync passing through onReject.

const { isPensing } = useAsync({ promiseFn: myFunction, onResolve: (data) => { console.log(data }, onReject: (error) => { // read Bad Request JSON response } })

The JSON Response I would like to read is:
{"id":"7282782728272827","status":"subscribed"}

Any idea ?
Thank you!

@ghengeveld
Copy link
Member

ghengeveld commented Dec 4, 2019

What you get as error in onReject is completely determined by what your promiseFn rejects with. It's up to you to make it return something useful. Here's what you could do when using fetch:

const myFunction = async () => {
  try {
    const res = await fetch(url)
    // try to parse the json, but there might not be any
    const data = await res.json()
    // resolve or reject with the json response data
    return res.ok ? data : Promise.reject(data) 
  } catch (e) {
    return Promise.reject(e) // we didn't get valid JSON
  }
}

However, this violates the type for error because it's now the json data, not an Error. There's several ways you can solve that:

  • Don't reject, but resolve with the error response. In other words just return data regardless of res.ok in the above example. This means you will have to take into account that your resolved data might actually contain an error. Still, it's the easiest solution.
  • Create a subclass of Error on which you add the response object. This is what useFetch does out of the box.
  • Use useFetch instead of useAsync and leverage the built-in error handling. When a request fails with useFetch, the error you get is a FetchError which exposes the response object as a property. It won't try to parse any JSON, but you can easily do that yourself. Here's an example:
const [error, setError] = useState()
const handleError = async error => {
  try {
    const data = await error.response.json()
    setError(data)
  } catch (e) {
    setError(e.message) // some other error
  }
}
const { data } = useFetch(url, { /* headers */ }, { onReject: handleError })

Arguably useFetch should probably try to parse a JSON response even for errors, so this wouldn't be necessary.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant