自定义错误消息是axios POST的响应体,在catch中抛出错误? (包括代码)

问题描述 投票:0回答:3

当我创建此 .NET 5 Web API 时,它通过“NotFound”返回错误,但包含带有其他错误信息的文本字符串,此自定义错误详细信息:

(a) 出现在 Postman 的响应体中,然而

(b) 我在 React Axios 代码的“捕获”错误中看不到错误信息(见下文)???

如何从 .NET 5 web api 访问如此详细的错误消息? “axios.post”请求工作正常,就在我模拟错误状态时,我正试图向我想传回的客户端获取额外的错误信息。

API 代码 (.NET 5)

var errorDetails = new
{
    error = "Custom error",
    message = "Custom message",
    details = "Custom details"
};
var errorDetailsJson = JsonSerializer.Serialize(errorDetails);
return NotFound(errorDetailsJson);

            
            

REACT / AXIOS 代码

try {
    let response = await axios.post(url, body, await getCustomAuthOptions('POST'));
    let data = await response.data;
    return data as T;
} catch (error) {
    console.log(error.toJSON());  // I CAN'T SEE THE RESPONSE BODY WITH CUSTOM ERROR MESSAGES HERE
    throw error;
}

CATCH 的 console.log 结果

{
  "message": "Request failed with status code 404",
  "name": "Error",
  "stack": "Error: Request failed with status code 404\n ...cut",
  "config": {
    "url": "https://localhost:5001/THE_URL_I_USE",
    "method": "post",
    "data": "",
    "headers": {
      "Accept": "application/json",
      "Content-Type": "application/json",
      "Authorization": "Bearer xxxetc"
    },
    "transformRequest": [
      null
    ],
    "transformResponse": [
      null
    ],
    "timeout": 0,
    "xsrfCookieName": "XSRF-TOKEN",
    "xsrfHeaderName": "X-XSRF-TOKEN",
    "maxContentLength": -1,
    "maxBodyLength": -1,
    "mode": "cors"
  }
}
reactjs asp.net asp.net-web-api axios http-error
3个回答
1
投票

正如@Greg 已经指出的那样。您可以从异常本身获取响应信息。参见示例:

try {
  let response = await axios.post(url, body, await getCustomAuthOptions('POST'));
  let data = await response.data;
  return data as T;
} catch (err) {
   //err.response.data is what you need
   console.error(err.response.data);  
}

1
投票

这是一个 axios 错误,所以你可以这样处理它:

axios
  .post(url, body, await getCustomAuthOptions("POST"))
  .then((response) => {
    let data = response.data;
    // Use your data here
  })
  .catch(function (error) {
    if (error.response) {
      // The request was made and the server responded with a status code
      // that falls out of the range of 2xx
      console.log(error.response.data);
      console.log(error.response.status);
      console.log(error.response.headers);
    } else if (error.request) {
      // The request was made but no response was received
      // `error.request` is an instance of XMLHttpRequest in the browser and an instance of
      // http.ClientRequest in node.js
      console.log(error.request);
    } else {
      // Something happened in setting up the request that triggered an Error
      console.log("Error", error.message);
    }
    console.log(error.config);
  });


1
投票
try {
    let response = await axios.post(url, body, await getCustomAuthOptions('POST'));
    let data = await response.data;
    return data as T;
} catch (error) {
    if (error.response && error.response.data) {
        let errorDetails = JSON.parse(error.response.data);
        console.log(errorDetails);
    }
    throw error;
}

使用此代码,如果 API 在响应正文中返回自定义错误消息,错误详细信息将记录到控制台。否则,将记录基本错误信息。请注意,您可能需要添加额外的错误处理逻辑来处理响应正文不包含有效 JSON 或不包含预期错误详细信息的情况。

© www.soinside.com 2019 - 2024. All rights reserved.