如果收到错误,如何从响应中获取数据?

时间:2020-11-02 09:14:25

标签: reactjs

如果收到404,如何获得后端错误? 这是我的代码:

export const myRequest = async (body: params) => {
  try {
    const result = await publicInstance.get('users', {
      params: body,
    });
    const { data } = result;
    return data;
  } catch (error) {
    console.error('Error:', error.message, error); // How to get data from response?
  }

  return {};
};

1 个答案:

答案 0 :(得分:0)

您将在响应中获取statusCode,您可以对其进行跟踪。根据状态代码,您可以放置​​自定义的错误消息。

export const myRequest = async (body: params) => {
  try {
    const result = await publicInstance.get('users', {
      params: body,
    });
    const { data } = result;
    return data;
  } catch (error) {
  
  if(error.statusCode == 404)
  error.message = "Unable to reach server at the moment. Please try again."

  console.error('Error:', error.message, error); 

  }

  return {};
};