如何在异步函数中捕获后端接口错误并传递错误信息
解决方案
要把后端返回的错误信息传递到catch块并更新通知内容,核心是在请求失败时抛出携带后端错误数据的异常,而不是return结果(return会让函数正常执行,不会触发catch)。具体步骤如下:
1. 修改错误抛出逻辑
在fetchData函数中,当response.ok为false时,不要return错误结果,而是抛出一个包含后端错误信息的Error对象(或直接抛出后端返回的错误对象):
方式一:规范的Error实例(推荐)
将后端返回的错误数据附加到Error对象上,保留Error实例的特性:
const fetchData = async () => { const response = await fetch("http://127.0.0.1:5000/api/cart"); const result = await response.json(); if (!response.ok) { // 创建Error实例,用后端的message作为错误提示 const error = new Error(result.message || "获取购物车数据失败"); // 把完整的后端错误响应挂载到error对象上 error.errorData = result; throw error; // 抛出异常,触发上层catch } else { return result; } };
方式二:直接抛出后端错误对象
如果不需要Error实例的特性,也可以直接抛出后端返回的错误对象:
const fetchData = async () => { const response = await fetch("http://127.0.0.1:5000/api/cart"); const result = await response.json(); if (!response.ok) { throw result; // 直接抛出后端错误对象 } else { return result; } };
2. 在catch块中读取错误信息并更新通知
修改catch块,读取抛出的错误数据,替换通知的message字段:
对应方式一的catch处理
catch (error) { // 优先使用后端返回的message, fallback到默认提示 const errorMessage = error.errorData?.message || error.message; dispatch( uiActions.showNotification({ status: "error", title: "Error!", message: errorMessage, }) ); }
对应方式二的catch处理
catch (error) { const errorMessage = error.message || "获取购物车数据失败"; dispatch( uiActions.showNotification({ status: "error", title: "Error!", message: errorMessage, }) ); }
修改后的完整函数(方式一)
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) { const error = new Error(result.message || "获取购物车数据失败"); error.errorData = result; throw error; } else { return result; } }; try { const cartData = await fetchData(); dispatch(cartActions.replaceCart(cartData)); } catch (error) { const errorMessage = error.errorData?.message || error.message; dispatch( uiActions.showNotification({ status: "error", title: "Error!", message: errorMessage, }) ); } }; }
内容的提问来源于stack exchange,提问作者dannisis
相关产品推荐
相关产品推荐

