提取API全局错误处理程序

时间:2018-07-12 04:15:04

标签: javascript fetch es6-promise

我正在将fetch API与REST API结合使用,并且我想在全球范围内处理某些错误,例如IF OBJECT_ID('dbo.fnConcatRowsPerGroup','FN') IS NOT NULL DROP FUNCTION dbo.fnConcatRowsPerGroup GO CREATE FUNCTION dbo.fnConcatRowsPerGroup (@grp as int) RETURNS VARCHAR(MAX) AS BEGIN DECLARE @val AS VARCHAR(MAX) SELECT @val = COALESCE(@val,'')+val FROM tbl WHERE grp = @grp RETURN @val; END GO select *, dbo.fnConcatRowsPerGroup(grp) from tbl 之类的错误,我曾尝试做类似的事情

500, 503 ...

但是它似乎不起作用。 如何在获取api中捕获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; });

2 个答案:

答案 0 :(得分:1)

以这种方式尝试这种方法,您可以在一个地方处理所有可能的错误,还可以生成自定义响应以返回,例如,如果所有请求都返回JSON数据,则可以在返回之前将响应转换为JSON。

for cell in tableView.visibleCells {
    cell.setSelected(false, animated: true)
}

tableView.reloadData()

答案 1 :(得分:-1)

在这里您可以像这样处理承诺:

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);

相关问题