首页 > 解决方案 > 抛出错误时,如何读取错误数据

问题描述

我正在尝试读取/处理 React JS 项目中的错误案例,但无法解析/读取 catch 中的错误数据。无法从错误数据中获取“代码”字段。

在此处输入图像描述

try {
  dispatch({ type: types.READ_DATA })
  const response = await new DataApi().readData(action.payload);
  processResponse(response, [200], "Read data failed", dispatch);
  dispatch({
    type: types.DATA_READ,
    data: response.data
  })
} catch (error) {
  console.error("MIDDLEWARE. CATCH ERROR: ", error);
  dispatch({ type: types.DATA_FAILED, data: { Code: error.code } })
}

const processResponse = (response, okCodes, errorMessage, dispatch) => {
if (response && response.status) {
  if (okCodes.indexOf(response.status) < 0) {
    errorHandler(response.status, dispatch);
    throw Error({ code: response.status, message: errorMessage });
  }
} else {
  throw Error("Error reading response status");
}
}

标签: reactjsreact-redux

解决方案


用于console.error(JSON.stringify(error))获取字符串格式的对象。


推荐阅读