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

标签 javascript reactjs error-handling server

我有一个有效的 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/

相关文章:

javascript - 从循环创建的表中提取数据 (PHP)

backbone.js - 如何将 React 测试实用程序与 Jasmine 一起使用

javascript - 警告 : Failed prop type: Invalid prop `children` of type `string` supplied to `Dropzone` , 应为 `function`

powershell - 如何在复制项目错误时捕获计算机名称?

php - 通过 PHP 脚本将 JSON 文件插入 MySQL

javascript - 动态 JavaScript If 语句

javascript - ASP.Net - AJAX 更新面板中的 Javascript

JavaScript 初始化回调链中的回调参数

plot - 在Gnuplot中使用方程式添加误差线

javascript - 我如何安装以前的版本 react-native-pdf