如何在Next.js与Prisma中实现自定义错误处理
解决Service层错误状态码传递问题
1. 定义自定义错误类
先创建携带状态码的自定义错误类,让错误信息能明确对应HTTP状态:
// utils/customError.js class CustomError extends Error { constructor(message, statusCode) { super(message); this.statusCode = statusCode; this.stack = new Error().stack; // 保留错误栈便于调试 } } export default CustomError;
2. 在Service层抛出对应错误
修改业务逻辑层,根据实际场景抛出带状态码的自定义错误:
// services/skillService.js import prisma from '@/lib/prisma'; import CustomError from '@/utils/customError'; export async function getAllSkills() { try { const skills = await prisma.skills.findMany({}); // 查询结果为空时抛出404错误 if (skills.length === 0) { throw new CustomError('No skills found', 404); } return skills; } catch (error) { // 捕获Prisma数据库相关错误,抛出500状态 if (error instanceof Prisma.PrismaClientKnownRequestError) { throw new CustomError('Database access failed', 500); } // 其他未知错误统一返回500 throw new CustomError(error.message || 'Server error', 500); } }
3. 路由层捕获错误并返回响应
在路由处理器里用try/catch捕获自定义错误,根据错误状态码返回对应HTTP响应:
// app/api/skills/route.js import { NextResponse } from 'next/server'; import { getAllSkills } from '@/services/skillService'; import CustomError from '@/utils/customError'; export async function GET() { try { const skills = await getAllSkills(); return NextResponse.json(skills); } catch (error) { // 识别自定义错误,返回对应状态码 if (error instanceof CustomError) { return NextResponse.json({ error: error.message }, { status: error.statusCode }); } // 兜底处理未知错误 return NextResponse.json({ error: 'Server error' }, { status: 500 }); } }
可选:全局错误处理(App Router)
如果是Next.js App Router,可在路由目录下创建error.js组件做页面级错误兜底(API路由仍需上述try/catch处理):
// app/api/skills/error.js 'use client'; // 必须添加客户端组件标识 export default function Error({ error, reset }) { return ( <div> <h2>请求出错了!</h2> <p>{error.message}</p> <button onClick={() => reset()}>重试</button> </div> ); }
这样既保持了业务逻辑与路由的解耦,又能精准返回对应HTTP状态码,不用把Prisma逻辑堆砌在路由处理器中。
内容的提问来源于stack exchange,提问作者MoLeo
相关产品推荐
相关产品推荐

