无法使用 axios 捕获请求错误

时间:2021-05-05 09:01:04

标签: reactjs axios fetch

我有以下代码,它应该用来捕获错误并从那里读取状态代码

 useEffect(async () => {
    try {
        const response = await apiSettingsSite.fetchProductsCalc();
        console.log(response)
    } catch (error) {
        console.log(error.response)
    }
},[])

但是当发生 400 错误时,我在控制台中从 try 块中得到 null,甚至没有触及来自 catch 的代码。与 .then .catch 相同

3 个答案:

答案 0 :(得分:1)

也许你有我这样使用的 axios 设置:

public async Task< IReadOnlyList<(String recipient, Boolean ok)> > PayCallSendSmsAsync( IEnumerable<SmsRequest> smsRequests )
{
    using( HttpClient httpClient = this.httpClientFactory.Create() )
    {
        var tasks = smsRequests
            .Select(r => SendSmsAsync(httpClient, r))
            .ToList(); // <-- The call to ToList is important as it materializes the list and triggers all of the Tasks.

        (String recipient, Boolean ok)[] results = await Task.WhenAll(tasks);
        return results;
    }
}

private static async Task<(String recipient, Boolean ok)> SendSmsAsync(HttpClient httpClient, SmsRequest smsRequest)
{
    using (HttpRequestMessage request = new HttpRequestMessage( ... ) )
    using (HttpResponseMessage response = await httpClient.SendAsync(request).ConfigureAwait(false))
    {
        String responseType = response.Content.Headers.ContentType?.MediaType ?? "";
        if (responseType != "application/json" || response.StatusCode != HttpStatusCode.OK)
        {
            throw new InvalidOperationException("Expected HTTP 200 JSON response but encountered an HTTP " + response.StatusCode + " " + responseType + " response instead." );
        }

        String jsonText = await response.Content.ReadAsStringAsync().ConfigureAwait(false);
        
        Dictionary<String,Object> dict = JsonConvert.DeserializeObject< Dictionary<String,Object> >(jsonText);

        if(
            dict != null &&
            dict.TryGetValue(STATUS, out Object statusValue) &&
            statusValue is String statusStr &&
            "true".Equals( statusStr, StringComparison.OrdinalIgnoreCase )
        )
        {
            return ( smsRequest.Recipient, ok: true );
        }
        else
        {
            return ( smsRequest.Recipient, ok: false );
        }
    }
}

答案 1 :(得分:1)

目前尚不清楚 fetchProductsCalc 函数内部的代码以及使用的 Axios 配置。

要在自己的端点上测试 Axios 请求,可以使用以下代码: Live sandbox

import React from "react";
import { useAsyncEffect } from "use-async-effect2";
import cpAxios from "cp-axios";

function TestComponent(props) {
  const [cancel, done, result, err] = useAsyncEffect(
    function* () {
      return (yield cpAxios(props.url)).data;
    },
    { states: true, deps: [props.url] }
  );

  return (
    <div className="component">
      <div className="caption">useAsyncEffect demo:</div>
      <div>
        {done ? (err ? err.toString() : JSON.stringify(result)) : "loading..."}
      </div>
      <button className="btn btn-danger" onClick={cancel} disabled={done}>
        Cancel async effect
      </button>
    </div>
  );
}

答案 2 :(得分:0)

您需要在 useEffect 内部创建异步函数,而不是将异步函数传递给 useEffect。

useEffect(() => {
  async function myFunc() {
    try {
      const response = await apiSettingsSite.fetchProductsCalc();
      console.log(response);
    } catch (error) {
      console.log(error.response);
    }
  };

  myFunc();
}, []);