
本文详解如何在 Next.js API Routes 中正确处理 Laravel 等外部 API 返回的业务错误(如 400/404/500),避免 Axios 默认将非 2xx 响应转为异常,确保前端能可靠显示后端返回的 message 等业务提示。
本文详解如何在 next.js api routes 中正确处理 laravel 等外部 api 返回的业务错误(如 400/404/500),避免 axios 默认将非 2xx 响应转为异常,确保前端能可靠显示后端返回的 `message` 等业务提示。
在 Next.js 的 API Routes 中调用第三方后端(如 Laravel)时,一个常见误区是:直接 throw e 或忽略错误响应,导致前端无法获取后端返回的结构化错误信息(例如 { success: false, message: "User is not registered." })。根本原因在于:Axios 默认将 HTTP 状态码不在 2xx 范围内的响应视为请求失败,并抛出 AxiosError,而你的 Next.js API Route 若未主动捕获并返回该错误体,前端就只能收到模糊的 500 Internal Server Error 或 ERR_BAD_RESPONSE。
✅ 正确做法:显式捕获 Axios 错误并返回结构化响应
你需要修改 API Route 的 catch 块,不再 throw e,而是解析并透传原始错误响应。关键点如下:
- 使用 axios.post() 的 validateStatus 选项(可选)或直接依赖 try/catch 捕获 AxiosError;
- 在 catch 中检查 error.response 是否存在——它包含后端返回的真实数据、状态码和 headers;
- 将 error.response.data 和 error.response.status 安全地包装进 NextResponse.json() 返回。
以下是修复后的 API Route 示例:
// app/api/forgot-password/route.ts (或 pages/api/forgot-password.ts)
import API from "@/lib/axios";
import { NextResponse } from "next/server";
export async function POST(req: Request) {
try {
const { email } = await req.json();
// ✅ 关键:Axios 会自动 reject 非 2xx 响应,此处 catch 即可捕获业务错误
const res = await API.post("/forgot-password", { email });
return NextResponse.json(
{
success: true,
message: res.data.message || "Password reset link sent.",
status: res.status,
},
{ status: 200 }
);
} catch (e) {
// ✅ 关键:不要 throw,而是提取并返回后端错误
if (e instanceof Error && "response" in e) {
const axiosError = e as any;
const errorData = axiosError.response?.data || {};
const statusCode = axiosError.response?.status || 500;
return NextResponse.json(
{
success: false,
message: errorData.message || "An unexpected error occurred.",
status: statusCode,
// 可选:添加 debug 字段(生产环境建议移除)
...(process.env.NODE_ENV === "development" && { debug: errorData }),
},
{ status: statusCode }
);
}
// 处理网络错误、超时等非响应错误
return NextResponse.json(
{
success: false,
message: "Network error. Please check your connection.",
status: 500,
},
{ status: 500 }
);
}
}
? 前端适配:在 useMutation 中处理业务错误
你当前的 useMutation 仅定义了 onSuccess,但未处理失败场景。需补充 onError 回调,从响应体中提取 message 并展示给用户:
const { isLoading: loading, mutate } = useMutation({
mutationFn: async (data: FormData) => {
const res = await axios.post("/api/forgot-password", data);
return res.data; // ✅ 返回解析后的 data,便于 onSuccess 使用
},
onSuccess: (data) => {
toast({
title: "Success",
description: data.message || "Password reset link sent successfully.",
variant: "default",
});
reset();
},
onError: (error: any) => {
// ✅ 提取 API Route 返回的业务错误消息
const errorMessage = error?.response?.data?.message
|| error?.message
|| "Failed to send reset link.";
toast({
title: "Error",
description: errorMessage,
variant: "destructive",
});
},
});
⚠️ 注意事项与最佳实践
- 不要依赖 throw e:Next.js API Route 中 throw 会触发默认 500 响应,丢失原始错误上下文;
- 始终检查 error.response:Axios 错误对象中,response 字段仅在服务器返回了 HTTP 响应时存在;若为空,则可能是网络层问题(DNS 失败、超时等);
- Laravel 后端需返回标准 HTTP 状态码:例如用户不存在时应返回 404 Not Found 或 400 Bad Request,而非统一 500 —— 这有助于前端区分错误类型;
- 开发期调试建议:在 catch 块中 console.error("API Error:", e),并检查浏览器 Network 面板中 /api/forgot-password 的响应内容与 Status Code;
- 安全性提醒:生产环境中避免向客户端暴露敏感 debug 信息(如完整堆栈、数据库字段名),仅返回用户友好的 message。
通过以上改造,你的前端即可稳定接收并展示 Laravel 后端返回的 "User is not registered." 等业务级错误提示,大幅提升用户体验与调试效率。
大量免费API接口:立即使用
涵盖生活服务API、金融科技API、企业工商API、等相关的API接口服务。免费API接口可安全、合规地连接上下游,为数据API应用能力赋能!










