How to include both a parsed response and original response headers in fetch errors [duplicate]

梦想与她 提交于 2019-12-01 10:52:46

Here's my helper for sane fetch error handling, fetchOk:

let fetchOk = (...args) => fetch(...args)
  .then(res => res.ok ? res : res.json().then(data => {
    throw Object.assign(new Error(data.error_message), {name: res.statusText});
  }));

Which I then substitute for fetch.

let fetchOk = (...args) => fetch(...args)
  .then(res => res.ok ? res : res.json().then(data => {
    throw Object.assign(new Error(data.error_message), {name: res.statusText});
  }));

fetchOk("https://api.stackexchange.com/2.2/blah")
  .then(response => response.json())
  .catch(e => console.log(e)); // Bad Request: no method found with this name

var console = { log: msg => div.innerHTML += msg + "<br>" };
<div id="div"></div>

It doesn't load the data unless there's an error, making it a direct replacement.

I use the new async/await syntax, since that reads in a more intuitive way:

 async fetchData(request) {
    try {
      const response = await fetch(request)
      const data = await response.json()

      // return the data if the response was ok
      if (response.ok) return { data }

      // otherwise return an error with the error data
      const error = new Error(response.statusText)
      if (data.errors) error.errors = data.errors

      throw error
    } catch (error) {
      return { error }
    }
  }

It makes it very easy to handle both the promise that fetch returns as well as the promise that response.json() returns.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!