我有一个有效的 API 可以从服务器获取项目,如下所示。我正在使用 React 来使用这些数据。现在,我想捕获所有以 5__ 开头的服务器错误,并显示一条消息,例如“没有与互联网连接”或类似的消息。
export const GetItems = (operand, searchValue) => {
const trimmedValue = searchValue.trim();
let combinedResults;
// make 2 API calls to search on both item_name and code;
// then combine them;
// there is no API method to do this, that I could find
return getItemsByName(operand, trimmedValue)
.then(result => (
(combinedResults = [].concat(result))
))
.then(() => getItemsByCode(operand, trimmedValue))
.then(result => (
(combinedResults = combinedResults.concat(result))
));
};
目前,我需要查看控制台来检查连接是否有问题。
已按照 @Dane 的要求进行更新
const getItemsByCode = (operand, searchValue) => (
FetchToJson(BuildCodeSearchUrl(operand, searchValue))
);
它只是调用一个方法来构建 URL。您可以认为一切正常,如果有连接就会得到响应。
最佳答案
使用catch()
:
return getItemsByName(operand, trimmedValue)
.then(result => (
(combinedResults = [].concat(result))
))
.then(() => getItemsByCode(operand, trimmedValue))
.then(result => (
(combinedResults = combinedResults.concat(result))
))
.catch((error) => {
if (error.response) { // if there is response, it means its not a 50x, but 4xx
} else { // gets activated on 50x errors, since no response from server
// do whatever you want here :)
}
});
关于javascript - React、JavaScript 中捕获 504(网关超时)错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47504868/