import { NextResponse } from 'next/server'; export type ErrorCode = | 'UNAUTHORIZED' | 'FORBIDDEN' | 'NOT_FOUND' | 'VALIDATION_ERROR' | 'INTERNAL_ERROR' | 'BAD_REQUEST'; export interface ApiError { error: string; code: ErrorCode; details?: Record; } const ERROR_MESSAGES: Record = { UNAUTHORIZED: '未授权,请先登录', FORBIDDEN: '无权限执行此操作', NOT_FOUND: '请求的资源不存在', VALIDATION_ERROR: '数据验证失败', INTERNAL_ERROR: '服务器内部错误', BAD_REQUEST: '请求参数错误', }; export function unauthorized(message?: string): NextResponse { return NextResponse.json( { error: message || ERROR_MESSAGES.UNAUTHORIZED, code: 'UNAUTHORIZED' }, { status: 401 } ); } export function forbidden(message?: string): NextResponse { return NextResponse.json( { error: message || ERROR_MESSAGES.FORBIDDEN, code: 'FORBIDDEN' }, { status: 403 } ); } export function notFound(message?: string): NextResponse { return NextResponse.json( { error: message || ERROR_MESSAGES.NOT_FOUND, code: 'NOT_FOUND' }, { status: 404 } ); } export function validationError(message: string, details?: Record): NextResponse { return NextResponse.json( { error: message, code: 'VALIDATION_ERROR', details }, { status: 400 } ); } export function badRequest(message: string): NextResponse { return NextResponse.json( { error: message, code: 'BAD_REQUEST' }, { status: 400 } ); } export function internalError(message = '服务器错误'): NextResponse { console.error(message); return NextResponse.json( { error: ERROR_MESSAGES.INTERNAL_ERROR, code: 'INTERNAL_ERROR' }, { status: 500 } ); } export function success(data: T, status = 200): NextResponse { return NextResponse.json(data, { status }); } export function handleApiError(error: unknown): NextResponse { console.error('API Error:', error); if (error instanceof Error) { if (error.message.includes('未授权')) { return unauthorized(error.message); } if (error.message.includes('无权限')) { return forbidden(error.message); } if (error.message.includes('不存在')) { return notFound(error.message); } } return internalError(); }