如何通过Axios在前端展示FastAPI返回的错误详情
解决FastAPI注册接口错误详情无法在Next.js前端展示的问题
要让前端显示account.create返回的具体错误原因,需要同时修改FastAPI后端和Next.js前端代码:
一、修改FastAPI后端代码
原来的异常捕获逻辑只返回403状态码,没有携带错误详情。需要将create函数抛出的错误信息放入HTTPException的detail字段,这样后端响应会包含具体错误内容:
from fastapi import HTTPException, status @app.post("/api/signup", status_code=status.HTTP_200_OK) async def signup(credentials: signupcred): try: print(credentials.email, credentials.password1, credentials.name ) response = account.create( email=credentials.email, password=credentials.password1, name=credentials.name, user_id=ID.unique() ) return response # 直接返回create的响应,无需额外包裹字典 except Exception as e: # 将错误详情传入detail,前端可通过响应体获取 raise HTTPException( status_code=status.HTTP_403_FORBIDDEN, detail=str(e) # 如果是自定义异常,可替换为e.message或对应错误属性 )
注意:如果account.create是返回错误对象而非抛出异常,需要先判断响应是否包含错误,再抛出对应HTTPException。
二、修改Next.js前端代码
Axios的错误对象中,error.response.data包含后端返回的完整响应数据,从中提取detail字段即可展示具体错误。同时补充不同错误场景的处理,避免只显示状态码提示:
const handlesignup = async (e: any) => { e.preventDefault(); setLoading((loading) => !loading); try { const signupresponse = await axios.post("/api/signup", { email: signupemail, password1: password1, name: name, }); router.replace("/dashboard"); setLoading((loading) => !loading); } catch (error: any) { let errorMessage = "注册失败,请稍后重试"; // 分场景处理错误信息 if (error.response) { // 服务器已返回响应,提取后端传来的错误详情 errorMessage = error.response.data.detail || "注册失败"; } else if (error.request) { // 请求已发送但无响应,提示网络问题 errorMessage = "网络异常,请检查连接后重试"; } alert(errorMessage); setLoading((loading) => !loading); // 重置加载状态,避免前端卡死 } };
内容的提问来源于stack exchange,提问作者C A OB1
相关产品推荐
相关产品推荐

