我有一个工作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。你可以认为一切都运行良好,如果有连接就得到响应。
答案 0 :(得分:1)
使用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 :)
}
});