How to handle HTTP code 4xx responses in fetch api

拜拜、爱过 提交于 2019-12-10 17:24:53

问题


I was wondering how we should handle 400 from backend when we use ajax function. We can make if statement in promise resolve function and check if res status is 400. Different approach is making wrapper service for fetch, and when we got 400 from server we throw exception. How to deal with that problem ?


回答1:


I'd suggest a wrapper that checks response.ok which will be true if the response code is 2xx.

Note this statement from the MDN page on fetch():

An accurate check for a successful fetch() would include checking that the promise resolved, then checking that the Response.ok property has a value of true. An HTTP status of 404 does not constitute a network error.

Here is a wrapper like this:

function fetchData() {
    return fetch.apply(null, arguments).then(function(response) {
         if (!response.ok) {
             // create error object and reject if not a 2xx response code
             var err = new Error("HTTP status code: " + response.status);
             err.response = response;
             err.status = response.status;
             throw err;
         }
         return response;
    });
}



回答2:


Incorporating it into your HTTP abstraction is probably a good idea. Perhaps with some sort of options argument:

const myFetch = (method, path, {headers, strictErrors, whatever}) => {
  // fetch here, if strictErrors is true, reject on error.
  // return a Promise.
}

myFetch('GET', 'somepath', {strictErrors: true})
  .then(response => {})
  .catch(err => { /* maybe 400 */ });

A wrapper around fetch is generally a good idea, fetch is a relatively low level function. Just as it isn't a good idea to directly create new XHR objects everywhere, I believe it isn't a good idea to directly call fetch() in various parts of your application. It's akin to a global variable, in some ways.



来源:https://stackoverflow.com/questions/40248231/how-to-handle-http-code-4xx-responses-in-fetch-api

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