gpt4 book ai didi

javascript - 在 React、JavaScript 中捕获 504(网关超时)错误

转载 作者:行者123 更新时间:2023-11-30 20:57:28 27 4
gpt4 key购买 nike

我有一个有效的 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))
));
};

目前,我需要查看控制台来检查连接是否有问题。

504 Gateway Timeout Error


根据@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/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com