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 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 | 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 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 1x 1x 1x 1x 1x 1x 1x 1x 1x 199x 199x 199x 199x 199x 199x 199x 199x 199x 199x 199x 199x 199x 199x 199x 199x 1x 1x 1x 1x 1x 1x 70x 70x 1x 1x 42x 42x 1x 1x 10x 10x 1x 1x 39x 39x 39x 39x 39x 1x 1x 1x 1x 1x 1x 4x 4x 1x 1x 1x 1x 1x 1x 3x 3x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 3x 3x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 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 11x 11x 11x 11x 11x 11x 11x 11x 11x 11x 14x 14x 14x 11x 11x 11x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 5x 5x 5x 4x 4x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 1x 1x 3x 3x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 4x 4x 4x 4x 4x 4x 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 300x 300x 300x 300x 300x 300x 171x 171x 171x 171x 129x 129x 300x 14x 24x 24x 14x 14x 14x 14x 14x 14x 115x 115x 285x 115x 285x 115x 115x 115x 300x 300x 300x 300x 300x 300x 300x 300x 300x 300x 300x 300x 300x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 981x 981x 981x 981x 981x 981x 981x 981x 943x 943x 38x 38x 38x 38x 38x 38x 38x 38x 38x 38x 38x 38x 38x 38x 38x 1x 1x 1x 1x 76x 76x 76x 76x 1824x 1824x 76x 76x 1x 1x 1x 1x 981x 981x 981x 981x 981x 981x 981x 981x 62x 62x 919x 919x 981x 881x 881x 38x 38x 38x 38x 38x 981x 981x 981x 981x 981x 981x 981x 981x 981x 981x 981x 981x 981x 981x 981x 981x 981x 981x 1x 1x 1x 1x 76x 76x 76x 76x 76x 76x 76x 76x 76x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 116x 116x 981x 981x 981x 981x 981x 981x 685x 685x 968x 296x 296x 296x 981x 981x 981x 981x 981x 981x 116x 116x 1x 1x 1x 1x 5x 5x 5x | /**
* API Error System
*
* Standardized error handling for API routes.
* Provides consistent error codes, custom error class, and error handler utility.
*/
import { NextResponse } from "next/server";
import { ZodError, ZodSchema } from "zod";
import { Prisma } from "@prisma/client";
import { logger } from "@/lib/logging";
import { errorResponse, ApiErrorResponse } from "./responses";
// ============================================================================
// ERROR CODES
// ============================================================================
/**
* Standard API error codes
* Use these codes for consistent error identification across the API
*/
export const ERROR_CODES = {
// Validation errors (400)
BAD_REQUEST: "BAD_REQUEST",
VALIDATION_ERROR: "VALIDATION_ERROR",
INVALID_ID: "INVALID_ID",
INVALID_INPUT: "INVALID_INPUT",
MISSING_REQUIRED_FIELD: "MISSING_REQUIRED_FIELD",
// Authentication errors (401)
UNAUTHORIZED: "UNAUTHORIZED",
INVALID_TOKEN: "INVALID_TOKEN",
TOKEN_EXPIRED: "TOKEN_EXPIRED",
SESSION_EXPIRED: "SESSION_EXPIRED",
// Authorization errors (403)
FORBIDDEN: "FORBIDDEN",
INSUFFICIENT_PERMISSIONS: "INSUFFICIENT_PERMISSIONS",
ADMIN_REQUIRED: "ADMIN_REQUIRED",
// Not found errors (404)
NOT_FOUND: "NOT_FOUND",
RESOURCE_NOT_FOUND: "RESOURCE_NOT_FOUND",
USER_NOT_FOUND: "USER_NOT_FOUND",
PRODUCT_NOT_FOUND: "PRODUCT_NOT_FOUND",
ORDER_NOT_FOUND: "ORDER_NOT_FOUND",
// Conflict errors (409)
CONFLICT: "CONFLICT",
DUPLICATE_ENTRY: "DUPLICATE_ENTRY",
ALREADY_EXISTS: "ALREADY_EXISTS",
EMAIL_IN_USE: "EMAIL_IN_USE",
// Business logic errors (422)
UNPROCESSABLE: "UNPROCESSABLE",
INSUFFICIENT_STOCK: "INSUFFICIENT_STOCK",
INSUFFICIENT_POINTS: "INSUFFICIENT_POINTS",
CART_EMPTY: "CART_EMPTY",
INVALID_PROMO_CODE: "INVALID_PROMO_CODE",
PAYMENT_FAILED: "PAYMENT_FAILED",
// Rate limiting (429)
RATE_LIMITED: "RATE_LIMITED",
TOO_MANY_REQUESTS: "TOO_MANY_REQUESTS",
// Server errors (500)
INTERNAL_ERROR: "INTERNAL_ERROR",
DATABASE_ERROR: "DATABASE_ERROR",
EXTERNAL_SERVICE_ERROR: "EXTERNAL_SERVICE_ERROR",
EMAIL_SEND_FAILED: "EMAIL_SEND_FAILED"} as const;
export type ErrorCode = (typeof ERROR_CODES)[keyof typeof ERROR_CODES];
// ============================================================================
// API ERROR CLASS
// ============================================================================
/**
* Custom API Error class for throwing structured errors
*
* @example
* throw new ApiError("VALIDATION_ERROR", "Invalid email format", 400);
* throw ApiError.notFound("Product");
* throw ApiError.unauthorized();
*/
export class ApiError extends Error {
public readonly code: ErrorCode;
public readonly status: number;
public readonly details?: unknown;
constructor(
code: ErrorCode,
message: string,
status = 400,
details?: unknown
) {
super(message);
this.name = "ApiError";
this.code = code;
this.status = status;
this.details = details;
// Maintains proper stack trace for where error was thrown
if (Error.captureStackTrace) {
Error.captureStackTrace(this, ApiError);
}
}
// -------------------------------------------------------------------------
// Static factory methods for common errors
// -------------------------------------------------------------------------
static validation(message: string, details?: unknown): ApiError {
return new ApiError(ERROR_CODES.VALIDATION_ERROR, message, 400, details);
}
static badRequest(message: string, details?: unknown): ApiError {
return new ApiError(ERROR_CODES.BAD_REQUEST, message, 400, details);
}
static invalidId(paramName = "id"): ApiError {
return new ApiError(ERROR_CODES.INVALID_ID, `Invalid ${paramName} parameter`, 400);
}
static notFound(resource: string, id?: string | number): ApiError {
const message = id
? `${resource} with ID '${id}' not found`
: `${resource} not found`;
return new ApiError(ERROR_CODES.NOT_FOUND, message, 404);
}
static unauthorized(message = "Authentication required"): ApiError {
return new ApiError(ERROR_CODES.UNAUTHORIZED, message, 401);
}
static forbidden(message = "Access denied"): ApiError {
return new ApiError(ERROR_CODES.FORBIDDEN, message, 403);
}
static adminRequired(): ApiError {
return new ApiError(ERROR_CODES.ADMIN_REQUIRED, "Admin access required", 403);
}
static conflict(message: string): ApiError {
return new ApiError(ERROR_CODES.CONFLICT, message, 409);
}
static duplicate(resource: string): ApiError {
return new ApiError(
ERROR_CODES.DUPLICATE_ENTRY,
`A ${resource} with this value already exists`,
409
);
}
static rateLimited(message = "Too many requests, please try again later"): ApiError {
return new ApiError(ERROR_CODES.RATE_LIMITED, message, 429);
}
static internal(message = "An unexpected error occurred"): ApiError {
return new ApiError(ERROR_CODES.INTERNAL_ERROR, message, 500);
}
static database(message = "Database operation failed"): ApiError {
return new ApiError(ERROR_CODES.DATABASE_ERROR, message, 500);
}
static insufficientStock(productName?: string): ApiError {
const message = productName
? `Insufficient stock for ${productName}`
: "Insufficient stock";
return new ApiError(ERROR_CODES.INSUFFICIENT_STOCK, message, 422);
}
static cartEmpty(): ApiError {
return new ApiError(ERROR_CODES.CART_EMPTY, "Cart is empty", 422);
}
static paymentFailed(message = "Payment processing failed"): ApiError {
return new ApiError(ERROR_CODES.PAYMENT_FAILED, message, 422);
}
}
// ============================================================================
// VALIDATION HELPERS
// ============================================================================
/**
* Validation error details for API responses
*/
export interface ValidationErrorDetail {
field: string;
message: string;
code: string;
}
/**
* Handle Zod validation error by throwing a standardized ApiError
*
* @param error - The ZodError to handle
* @throws ApiError with VALIDATION_ERROR code and field details
*
* @example
* const result = schema.safeParse(body);
* if (!result.success) {
* handleValidationError(result.error);
* }
*/
export function handleValidationError(error: ZodError): never {
const firstIssue = error.issues[0];
const field = firstIssue.path.join(".");
const message = field
? `${field}: ${firstIssue.message}`
: firstIssue.message;
throw new ApiError(ERROR_CODES.VALIDATION_ERROR, message, 400, {
code: "VALIDATION_ERROR",
details: error.issues.map((issue) => ({
field: issue.path.join("."),
message: issue.message,
code: issue.code,
})),
});
}
/**
* Validate request body against a Zod schema
*
* Parses the body and throws a standardized ApiError if validation fails.
* Use this instead of manual .safeParse() + error handling.
*
* @param schema - The Zod schema to validate against
* @param body - The request body to validate
* @returns The parsed and validated data
* @throws ApiError with VALIDATION_ERROR code if validation fails
*
* @example
* export const POST = withErrorHandling(async (request) => {
* const body = await request.json();
* const data = validateBody(CreateProductSchema, body);
* // data is now typed and validated
* const product = await prisma.product.create({ data });
* return createdResponse(product);
* });
*/
export function validateBody<T>(schema: ZodSchema<T>, body: unknown): T {
const result = schema.safeParse(body);
if (!result.success) {
handleValidationError(result.error);
}
return result.data;
}
/**
* Validate query parameters against a Zod schema
*
* @param schema - The Zod schema to validate against
* @param params - The query parameters to validate (URLSearchParams or object)
* @returns The parsed and validated parameters
* @throws ApiError with VALIDATION_ERROR code if validation fails
*
* @example
* export const GET = withErrorHandling(async (request) => {
* const { searchParams } = new URL(request.url);
* const params = validateQuery(ListQuerySchema, Object.fromEntries(searchParams));
* // params is now typed and validated
* const products = await prisma.product.findMany({ where: params });
* return successResponse(products);
* });
*/
export function validateQuery<T>(
schema: ZodSchema<T>,
params: URLSearchParams | Record<string, string | string[] | undefined>
): T {
const paramsObj =
params instanceof URLSearchParams
? Object.fromEntries(params.entries())
: params;
const result = schema.safeParse(paramsObj);
if (!result.success) {
handleValidationError(result.error);
}
return result.data;
}
/**
* Validate route parameters against a Zod schema
*
* @param schema - The Zod schema to validate against
* @param params - The route parameters
* @returns The parsed and validated parameters
* @throws ApiError with VALIDATION_ERROR code if validation fails
*
* @example
* export const GET = withErrorHandling(async (request, { params }) => {
* const { id } = validateParams(RouteParamsSchema, await params);
* const product = await prisma.product.findUnique({ where: { id } });
* return successResponse(product);
* });
*/
export function validateParams<T>(
schema: ZodSchema<T>,
params: Record<string, string>
): T {
const result = schema.safeParse(params);
if (!result.success) {
handleValidationError(result.error);
}
return result.data;
}
// ============================================================================
// ERROR HANDLER
// ============================================================================
/**
* Convert any error to a standardized API error response
*
* Handles:
* - ApiError instances
* - Zod validation errors
* - Prisma database errors
* - Generic JavaScript errors
*
* @example
* try {
* // ... API logic
* } catch (error) {
* return handleApiError(error, "GET /api/products");
* }
*/
export function handleApiError(
error: unknown,
context?: string
): NextResponse<ApiErrorResponse> {
// Handle known ApiError
if (error instanceof ApiError) {
return errorResponse(error.code, error.message, {
status: error.status,
details: error.details});
}
// Handle Zod validation errors
if (error instanceof ZodError) {
const details = error.issues.map((issue) => ({
field: issue.path.join("."),
message: issue.message,
code: issue.code}));
return errorResponse(ERROR_CODES.VALIDATION_ERROR, "Validation failed", {
status: 400,
details});
}
// Handle Prisma errors
if (error instanceof Prisma.PrismaClientKnownRequestError) {
return handlePrismaError(error, context);
}
if (error instanceof Prisma.PrismaClientValidationError) {
logger.error(`Prisma validation error${context ? ` in ${context}` : ""}`, error, { category: 'API' });
return errorResponse(ERROR_CODES.VALIDATION_ERROR, "Invalid data format", {
status: 400});
}
// Log unknown errors
logger.error(
`Unhandled error${context ? ` in ${context}` : ""}`,
error instanceof Error ? error : new Error(String(error)),
{ category: 'API' }
);
// Return generic error for unknown errors (don't expose details in production)
const isDev = process.env.NODE_ENV === "development";
return errorResponse(
ERROR_CODES.INTERNAL_ERROR,
isDev && error instanceof Error ? error.message : "An unexpected error occurred",
{ status: 500 }
);
}
/**
* Handle Prisma-specific errors
*/
function handlePrismaError(
error: Prisma.PrismaClientKnownRequestError,
context?: string
): NextResponse<ApiErrorResponse> {
switch (error.code) {
// Unique constraint violation
case "P2002": {
const target = (error.meta?.target as string[])?.join(", ") || "field";
return errorResponse(
ERROR_CODES.DUPLICATE_ENTRY,
`A record with this ${target} already exists`,
{ status: 409 }
);
}
// Record not found
case "P2025":
return errorResponse(ERROR_CODES.NOT_FOUND, "Record not found", {
status: 404});
// Foreign key constraint failed
case "P2003":
return errorResponse(
ERROR_CODES.VALIDATION_ERROR,
"Referenced record does not exist",
{ status: 400 }
);
// Required relation not found
case "P2018":
return errorResponse(
ERROR_CODES.NOT_FOUND,
"Required related record not found",
{ status: 404 }
);
// Value too long for column
case "P2000":
return errorResponse(
ERROR_CODES.VALIDATION_ERROR,
"Value is too long for this field",
{ status: 400 }
);
default:
logger.error(
`Prisma error ${error.code}${context ? ` in ${context}` : ""}`,
error,
{ category: 'API' }
);
return errorResponse(ERROR_CODES.DATABASE_ERROR, "Database operation failed", {
status: 500});
}
}
// ============================================================================
// ROUTE WRAPPER
// ============================================================================
import { NextRequest } from "next/server";
import { prisma } from "@/lib/prisma";
type RouteHandler<T = unknown> = (
request: NextRequest,
context?: { params: Promise<Record<string, string>> }
) => Promise<NextResponse<T>>;
/**
* Record HTTP metric to database (non-blocking)
*/
function recordHttpMetric(
method: string,
path: string,
statusCode: number,
duration: number
): void {
// Skip if prisma.httpMetric is not available (e.g., in tests with incomplete mocks)
if (!prisma?.httpMetric?.create) {
return;
}
// Fire and forget - don't await
prisma.httpMetric
.create({
data: {
method,
path: normalizePath(path),
statusCode,
duration,
timestamp: new Date(),
},
})
.catch((err) => {
logger.warn('Failed to record HTTP metric', {
category: 'METRICS',
error: err instanceof Error ? err.message : 'Unknown error',
});
});
}
/**
* Generate hex ID for traces/spans
*/
function generateHexId(length: number): string {
const chars = '0123456789abcdef';
let result = '';
for (let i = 0; i < length; i++) {
result += chars[Math.floor(Math.random() * chars.length)];
}
return result;
}
/**
* Record trace to database (non-blocking)
*/
function recordTrace(
method: string,
path: string,
statusCode: number,
duration: number
): void {
// Skip recording for admin monitoring routes to avoid infinite loops
if (path.includes('/admin/monitoring/')) {
return;
}
// Skip if prisma.trace is not available (e.g., in tests with incomplete mocks)
if (!prisma?.trace?.create) {
return;
}
const traceId = generateHexId(32);
const spanId = generateHexId(16);
const now = new Date();
const startTime = new Date(now.getTime() - duration);
const status = statusCode >= 400 ? 'error' : 'ok';
const name = `${method} ${normalizePath(path)}`;
// Fire and forget - create trace first, then span
prisma.trace.create({
data: {
id: traceId,
name,
serviceName: 'elite-events',
startTime,
endTime: now,
duration,
status,
},
}).then(() => {
return prisma.span.create({
data: {
id: spanId,
traceId,
name,
kind: 'server',
startTime,
endTime: now,
duration,
status,
},
});
}).catch((err) => {
// Log to console in development for debugging
if (process.env.NODE_ENV === 'development') {
console.error('[TRACE ERROR]', err instanceof Error ? err.message : err);
}
logger.warn('Failed to record trace', {
category: 'METRICS',
error: err instanceof Error ? err.message : 'Unknown error',
});
});
}
/**
* Normalize path by replacing dynamic segments with placeholders
*/
function normalizePath(path: string): string {
return path
.replace(
/[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}/gi,
':id'
)
.replace(/\/\d+(?=\/|$)/g, '/:id')
.substring(0, 500);
}
/**
* Wrap a route handler with automatic error handling and metrics recording
*
* @example
* export const GET = withErrorHandling(async (request, { params }) => {
* const { id } = await params;
* const product = await prisma.product.findUnique({ where: { id: parseInt(id) } });
* if (!product) throw ApiError.notFound("Product", id);
* return successResponse(product);
* });
*/
export function withErrorHandling<T>(handler: RouteHandler<T>): RouteHandler<T | ApiErrorResponse> {
return async (request, context) => {
const startTime = Date.now();
const url = new URL(request.url);
let statusCode = 500;
try {
const response = await handler(request, context);
statusCode = response.status;
return response;
} catch (error) {
const errorResponse = handleApiError(error, `${request.method} ${url.pathname}`);
statusCode = errorResponse.status;
return errorResponse;
} finally {
// Record metrics asynchronously (don't block response)
const duration = Date.now() - startTime;
recordHttpMetric(request.method, url.pathname, statusCode, duration);
recordTrace(request.method, url.pathname, statusCode, duration);
}
};
}
/**
* Type guard to check if an error is an ApiError
*/
export function isApiError(error: unknown): error is ApiError {
return error instanceof ApiError;
}
|