简体   繁体   English

异步捕获后端错误的正确方法 function

[英]correct way to catch error from backend in a async function

The response.json() from a backend is an data object which can be if request is OK:来自后端的response.json()是一个数据 object 如果请求正常,它可以是:

{
    "items": [
        {
            "id": "p2",
            "name": "My Second Book",
            "price": 8.98,
            "quantity": 2,
            "totalPrice": 17.96
        },
        {
            "id": "p1",
            "name": "My First Book",
            "price": 6.99,
            "quantity": 3,
            "totalPrice": 20.97
        }
    ],
    "totalQuantity": 5
}

Or if there any error, it responses with this object:或者,如果有任何错误,它会以 object 响应:

{
    "code": 404,
    "description": "The requested URL was not found on the server. If you entered the URL manually please check your spelling and try again.",
    "message": "Not Found"
}

The function for fetching request exports dispatch result. function 用于获取请求导出派发结果。

export function fetchCartData() {
  return async (dispatch) => {
    const fetchData = async () => {
      const response = await fetch("http://127.0.0.1:5000/api/cart");
      const result = await response.json();
      if (!response.ok) {
        console.log(result);
        throw new Error(result);
      } else {
        console.log(result);
        return result;
      }
    };
    try {
      const cartData = await fetchData();
      dispatch(cartActions.replaceCart(cartData));
    } catch (error) {
      // console.log(error);
      dispatch(
        uiActions.showNotification({
          status: "error",
          title: "Error!",
          message: "Fetching cart data failed!",
        })
      );
    }
  };
}

The goal of fetchData function nested is sending GET request to API, store OK or not OK response in constant result and pass it to try-catch for handle response or error. fetchData function 嵌套的目的是向 API 发送GET请求,将 OK 或 not OK 响应存储在常量result中,并将其传递给try-catch以处理响应或错误。

if response is OK in fetchData function, try dispatch it, but when response is not OK the object result brings information such message: Not Found which I want to pass to catch(error) for replacing in message into 'dispatch(uiActions.showNotification({message:` key.如果在fetchData function 中response is OK ,请try调度它,但是当response is not OK时,object 结果会带来这样的message: Not Found我想传递给catch(error)以将消息替换为 'dispatch(uiActions.showNotification( {消息:`键。

I tried returning result when response is not OK but it still does not pass object to catch , for example:我尝试在响应不正确时返回result ,但它仍然没有将 object 传递给catch ,例如:

if (!response.ok) {
   console.log(result);
   return result;
   } 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM