fetchJson.js 601 B

123456789101112131415161718192021222324
  1. export default async function fetcher(...args) {
  2. try {
  3. const response = await fetch(...args)
  4. // if the server replies, there's always some data in json
  5. // if there's a network error, it will throw at the previous line
  6. const data = await response.json()
  7. if (response.ok) {
  8. return data
  9. }
  10. const error = new Error(response.statusText)
  11. error.response = response
  12. error.data = data
  13. throw error
  14. } catch (error) {
  15. if (!error.data) {
  16. error.data = { message: error.message }
  17. }
  18. throw error
  19. }
  20. }