All files / src/lib error-handler.ts

89.07% Statements 163/183
86.66% Branches 26/30
58.82% Functions 10/17
89.07% Lines 163/183

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 1841x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 15x 15x 15x 15x 15x 3x 3x 3x 3x 3x 3x         3x 3x 3x 12x 12x 15x 3x 3x 3x 4x 4x 4x 4x 4x 3x 3x 3x 3x 3x 3x 3x 3x 3x 9x 9x 15x 1x 1x 1x 1x 1x 1x 8x 8x 15x 4x 4x 4x 4x 1x 1x 1x 1x 1x 3x 3x 4x 1x 1x 1x 1x 1x 2x 2x 4x           4x 6x 6x 6x 6x 6x 6x 6x 6x 1x 1x 1x 1x 1x 1x 1x 1x 3x 3x 3x 3x 3x 3x 3x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x                        
/**
 * Centralized error handling for API routes
 * Provides consistent error responses with proper HTTP status codes
 */
 
import { NextResponse } from "next/server";
import { ZodError } from "zod";
import { logger } from "@/lib/logging";
import {
  AppError,
  AuthenticationError,
  AuthorizationError,
  NotFoundError,
  ValidationError,
  ConflictError,
  RateLimitError,
  isAppError } from "@/lib/errors";
 
// Re-export error classes for convenience
export {
  AppError,
  AuthenticationError,
  AuthorizationError,
  NotFoundError,
  ValidationError,
  ConflictError,
  RateLimitError } from "@/lib/errors";
 
/**
 * Error response format
 */
interface ErrorResponse {
  error: string;
  code: string;
  details?: Record<string, unknown>;
}
 
/**
 * Handle errors and return appropriate NextResponse
 * @param error The error that occurred
 * @returns NextResponse with appropriate status code and error message
 */
export function handleError(error: unknown): NextResponse {
  logger.error("API Error", error instanceof Error ? error : new Error(String(error)), { category: 'API' });
 
  // Handle custom AppError and all its subclasses
  if (isAppError(error)) {
    const response: ErrorResponse = {
      error: error.message,
      code: error.code};
 
    // Add retry-after header for rate limit errors
    if (error instanceof RateLimitError && error.retryAfter) {
      return NextResponse.json(response, {
        status: error.statusCode,
        headers: { "Retry-After": error.retryAfter.toString() }});
    }
 
    return NextResponse.json(response, { status: error.statusCode });
  }
 
  // Handle Zod validation errors
  if (error instanceof ZodError) {
    const errors: Record<string, string[]> = {};
 
    error.issues.forEach((issue) => {
      const path = issue.path.join(".");
      if (!errors[path]) {
        errors[path] = [];
      }
      errors[path].push(issue.message);
    });
 
    const response: ErrorResponse = {
      error: "Validation failed",
      code: "VALIDATION_ERROR",
      details: errors};
 
    return NextResponse.json(response, { status: 400 });
  }
 
  // Handle JSON parsing errors
  if (error instanceof SyntaxError) {
    const response: ErrorResponse = {
      error: "Invalid request body",
      code: "INVALID_JSON"};
 
    return NextResponse.json(response, { status: 400 });
  }
 
  // Handle Prisma errors
  if (error instanceof Error) {
    const message = error.message || "Unknown error";
 
    // Prisma unique constraint violation
    if (message.includes("Unique constraint failed")) {
      const response: ErrorResponse = {
        error: "Record already exists",
        code: "UNIQUE_CONSTRAINT_FAILED"};
      return NextResponse.json(response, { status: 409 });
    }
 
    // Prisma record not found
    if (message.includes("not found") || message.includes("not exist")) {
      const response: ErrorResponse = {
        error: "Record not found",
        code: "NOT_FOUND"};
      return NextResponse.json(response, { status: 404 });
    }
 
    // Prisma foreign key constraint
    if (message.includes("Foreign key constraint failed")) {
      const response: ErrorResponse = {
        error: "Related record not found",
        code: "FOREIGN_KEY_CONSTRAINT_FAILED"};
      return NextResponse.json(response, { status: 400 });
    }
  }
 
  // Generic internal server error
  const response: ErrorResponse = {
    error: "Internal server error",
    code: "INTERNAL_ERROR"};
 
  return NextResponse.json(response, { status: 500 });
}
 
/**
 * Create a standardized error response
 * @param message Error message
 * @param statusCode HTTP status code
 * @param code Error code for frontend handling
 * @returns AppError instance
 */
export function createError(
  message: string,
  statusCode: number = 500,
  code: string = "INTERNAL_ERROR"
): AppError {
  return new AppError(message, statusCode, code);
}
 
/**
 * Common error creators for easy use
 */
export const errors = {
  unauthorized: (message = "Unauthorized") =>
    new AuthenticationError(message),
 
  forbidden: (message = "Forbidden") =>
    new AuthorizationError(message),
 
  notFound: (resource = "Resource") =>
    new NotFoundError(resource),
 
  conflict: (message = "Conflict") =>
    new ConflictError(message),
 
  validation: (message = "Validation failed", field?: string) =>
    new ValidationError(message, field),
 
  rateLimit: (message = "Too many requests", retryAfter?: number) =>
    new RateLimitError(message, retryAfter),
 
  internal: (message = "Internal server error") =>
    createError(message, 500, "INTERNAL_ERROR")};
 
/**
 * API handler wrapper that catches errors and returns proper responses
 * @param handler The API handler function
 * @returns Wrapped handler with error handling
 */
export function withErrorHandling<T>(
  handler: (request: Request, context?: T) => Promise<NextResponse>
): (request: Request, context?: T) => Promise<NextResponse> {
  return async (request: Request, context?: T) => {
    try {
      return await handler(request, context);
    } catch (error) {
      return handleError(error);
    }
  };
}