{"record":{"id":"f6fae3a3c1b4e484","repo":"affaan-m/ECC","slug":"internal-error","errorCode":"INTERNAL_ERROR","errorMessage":"An unexpected error occurred","messagePattern":"An unexpected error occurred","errorType":"http","errorClass":null,"httpStatus":500,"severity":"error","filePath":"skills/error-handling/SKILL.md","lineNumber":153,"sourceCode":"    return NextResponse.json(\n      {\n        error: {\n          code: 'VALIDATION_ERROR',\n          message: 'Request validation failed',\n          details: error.issues.map(i => ({\n            field: i.path.join('.'),\n            message: i.message,\n          })),\n        },\n      },\n      { status: 422 },\n    )\n  }\n\n  // Unexpected error — log details, return generic message\n  console.error('Unexpected error:', error)\n  return NextResponse.json(\n    { error: { code: 'INTERNAL_ERROR', message: 'An unexpected error occurred' } },\n    { status: 500 },\n  )\n}\n\nexport async function POST(req: NextRequest) {\n  try {\n    // ... handler logic\n  } catch (error) {\n    return handleApiError(error)\n  }\n}\n```\n\n### React Error Boundary\n\n```typescript\nimport { Component, ErrorInfo, ReactNode } from 'react'\n","sourceCodeStart":135,"sourceCodeEnd":171,"githubUrl":"https://github.com/affaan-m/ECC/blob/d8409a4b0813771235555e32e3d8046a73988bfa/skills/error-handling/SKILL.md#L135-L171","documentation":"The catch-all branch of handleApiError in the error-handling skill: any thrown error that is neither the custom ApiError nor a z.ZodError is logged server-side with console.error('Unexpected error:', error) and returned to the client as HTTP 500 with a generic { code: 'INTERNAL_ERROR', message: 'An unexpected error occurred' } body. The design deliberately hides internals (stack traces, driver messages) from the client while preserving them in server logs.","triggerScenarios":"A database/Redis/Supabase connection failure inside the handler; an unguarded TypeError (reading a property of undefined from a null DB row); a missing environment variable used at call time; JSON.stringify choking on a BigInt or circular structure; a third-party SDK throwing its own error type.","commonSituations":"Env var present locally but missing in the deployed environment; a null database record dereferenced without a check; external service outage surfacing as a raw driver exception; Date/BigInt serialization bugs that only appear with real data.","solutions":["Check the server-side logs for the 'Unexpected error:' line — the real error and stack are there, not in the 4xx/500 response body","Reproduce the request locally and add a temporary breakpoint or log around the failing call","Once identified, handle that failure explicitly (custom ApiError with the right status, or a null check) instead of letting it fall through","If it is a missing env var, validate required secrets at startup so the app fails fast with a clear message"],"exampleFix":"// before - null row falls through to the 500 catch-all\nconst user = await db.user.findUnique({ where: { id } })\nreturn NextResponse.json({ data: user.profile })  // user is null -> TypeError -> 500\n\n// after - explicit check with a specific error\nconst user = await db.user.findUnique({ where: { id } })\nif (!user) throw new ApiError(404, 'User not found')\nreturn NextResponse.json({ data: user.profile })","handlingStrategy":"try-catch","validationCode":"// Fail fast on required config at startup so this 500 never originates from missing env\nconst REQUIRED = ['DATABASE_URL', 'JWT_SECRET'] as const\nfor (const key of REQUIRED) {\n  if (!process.env[key]) throw new Error(`Missing required env var: ${key}`)\n}","typeGuard":null,"tryCatchPattern":"// Keep the ordered cascade: known errors first, generic last, and always log the cause server-side\ntry {\n  return await handler(req)\n} catch (error) {\n  if (error instanceof ApiError) return respond(error.statusCode, error.code, error.message)\n  if (error instanceof z.ZodError) return respond422(error.issues)\n  console.error('Unexpected error:', error) // full stack stays in server logs\n  return respond(500, 'INTERNAL_ERROR', 'An unexpected error occurred') // client-safe\n}","preventionTips":["Never debug from the 500 response body — it is deliberately generic; go to the server log line 'Unexpected error:'","Validate required environment variables at process start, not lazily at request time","Narrow nullable DB results explicitly before property access","Add integration tests that exercise error paths, not just happy paths, so unexpected throws surface before deploy"],"tags":["api","http-500","error-handling","nextjs"],"backgroundTag":"unhandled-server-exception","analyzedSha":"d8409a4b0813771235555e32e3d8046a73988bfa","analyzedAt":"2026-08-26T12:15:34.022Z","contentChangedAt":null,"schemaVersion":2},"datasetVersion":"2026-09-14T00:17:10.932Z"}