获取 API 全局错误处理程序

问题描述 投票:0回答:2

我正在使用带有 REST API 的 fetch API,并且我想全局处理某些错误,例如

500, 503 ...
我尝试做这样的事情

function(url, method, data) {
    return fetch(url, {
        method: method || "GET",
        body: JSON.stringify(data),
        mode: "cors",
        headers: {
        "Content-Type": "application/json; charset=utf-8"
        }
    }).then(response => {

        if (response.ok && response.status < 500) console.log("ouch");;

        return response;

});

但它似乎不起作用。 如何在 fetch api 中捕获

500, 503 ...

javascript fetch es6-promise
2个回答
13
投票

您可以尝试以下方法,通过使用它您可以在一个地方处理所有可能的错误并生成自定义响应以返回例如如果所有请求都返回 JSON 数据,那么您可以在返回之前将响应转换为 JSON。

function secureFetch(url, method, data) {
  return fetch(url, {
    method: method || "GET",
    body: JSON.stringify(data),
    mode: "cors",
    headers: {
      "Content-Type": "application/json; charset=utf-8"
    }
  }).then(response => {
    // Server returned a status code of 2XX
    if (response.ok) {
      // you can call response.json() here if you want to return the json
      return response;
    }

    // Server returned a status code of 4XX or 5XX
    // Throw the response to handle it in the next catch block
    throw response;
  }).catch(error => {
    // It will be invoked for network errors and errors thrown from the then block
    // Do what ever you want to do with error here
    if (error instanceof Response) {
      // Handle error according to the status code
      switch (error.status) {
        case 404:
          // You can also call global notification service here
          // to show a notification to the user
          // notificationService.information('Object not found');
          console.log('Object not found');
          break;
        case 500:
          console.log('Internal server error');
          break;
        default:
          console.log('Some error occurred');
          break;
      }
    } else {
      // Handle network errors
      console.log('Network error');
      console.log(error);
    }
    // In case you don't want to throw the error just return some value here
    // This will be returned to the then block as a resolved promise
    // return { success: false };

    // Here you can throw a custom error too
    // throw new Error('Something went wrong');
    throw error;
  });
}


secureFetch('https://jsonplaceholder.typicode.com/posts/1')
.then(response => response.json())
.then(json => console.log(json))
.catch(error => console.log(error));

secureFetch('https://jsonplaceholder.typicode.com/posts/100000000')
.then(response => response.json())
.then(json => console.log(json))
.catch(error => console.log(error));


-1
投票

在这里你可以用 Promise 来处理这样的事情:

function status(response) {
    /*You can handle status here.*/
    if (response.status >= 200 && response.status < 300) {
      return Promise.resolve(response)
    } else {
      return Promise.reject(new Error(response.statusText))
    }
  }

  function json(response) {
    return response.json()
  }
function makeCall(url, method, data) {
    return fetch(url, {
        method: method || "GET",
        body: JSON.stringify(data),
        mode: "cors",
        headers: {
        "Content-Type": "application/json; charset=utf-8"
        }
    })
    .then(status)
    .then(json)
    .then(function(data) {
    	console.log('Request succeeded with JSON response', data);
    }).catch(function(error) {
      console.log('Request failed', error);
    });
}

var url = 'http://localhost:4200/profile';
var data = {username: 'example'};
makeCall(url, 'POST', data);

© www.soinside.com 2019 - 2024. All rights reserved.