如何在Next.js API路由中返回错误及上下文,让前端知晓具体原因?
解决前端无法获取具体错误信息的问题
你的核心问题是NextResponse.error(error)会返回通用500错误,不会将自定义错误消息传递给前端。要让客户端明确错误原因,需要手动返回包含具体信息的JSON响应,而非依赖默认的错误处理。
方案1:直接返回带具体信息的JSON响应
修改catch块,判断错误类型后返回包含自定义消息和状态码的JSON:
export async function POST(req: Request) { try { const customer = null; if (!customer) throw new Error("Could not get customer"); return NextResponse.json({ message: "hello world", }); } catch (error) { // 处理自定义抛出的Error if (error instanceof Error) { return NextResponse.json( { error: error.message, errorType: "CUSTOMER_NOT_FOUND" // 可选,方便前端快速识别错误类型 }, { status: 404 } // 用符合语义的状态码,比如404表示资源未找到 ); } // 处理其他未知错误 return NextResponse.json( { error: "Internal server error" }, { status: 500 } ); } }
这样前端就能拿到明确的错误消息,甚至可以通过errorType字段做针对性的逻辑处理,比如显示“用户不存在”的提示。
方案2:自定义错误类(适合多错误场景)
如果你的API需要处理多种错误类型,可以创建自定义错误类来规范错误结构:
// 定义自定义错误类 class ApiError extends Error { statusCode: number; errorType: string; constructor(message: string, statusCode: number, errorType: string) { super(message); this.statusCode = statusCode; this.errorType = errorType; Object.setPrototypeOf(this, ApiError.prototype); } } export async function POST(req: Request) { try { const customer = null; if (!customer) { throw new ApiError("Could not get customer", 404, "CUSTOMER_NOT_FOUND"); } return NextResponse.json({ message: "hello world", }); } catch (error) { if (error instanceof ApiError) { return NextResponse.json( { error: error.message, errorType: error.errorType }, { status: error.statusCode } ); } // 兜底处理未知错误 return NextResponse.json( { error: "Internal server error" }, { status: 500 } ); } }
这种方式能让错误处理更结构化,前端可以根据errorType快速区分不同错误,比如区分“用户不存在”和“参数错误”。
关键说明
NextResponse.error()的设计是返回通用服务器错误,不会暴露自定义错误细节。手动返回JSON响应可以精准控制错误信息的传递,同时通过指定正确的HTTP状态码(如404、400),让前端更清晰地判断错误类型。
内容的提问来源于stack exchange,提问作者Ripas55
相关产品推荐
相关产品推荐

