| 63 | * Handles unexpected errors with consistent logging and response. |
| 64 | */ |
| 65 | export function handleError( |
| 66 | requestId: string, |
| 67 | error: unknown, |
| 68 | defaultMessage: string |
| 69 | ): NextResponse { |
| 70 | const validationResponse = validationErrorResponseFromError(error) |
| 71 | if (validationResponse) return validationResponse |
| 72 | |
| 73 | if (error instanceof Error) { |
| 74 | if (error.message.includes('does not have permission')) { |
| 75 | return NextResponse.json({ error: 'Access denied' }, { status: 403 }) |
| 76 | } |
| 77 | |
| 78 | const isStorageLimitError = |
| 79 | error.message.includes('Storage limit exceeded') || error.message.includes('storage limit') |
| 80 | if (isStorageLimitError) { |
| 81 | return NextResponse.json({ error: 'Storage limit exceeded' }, { status: 413 }) |
| 82 | } |
| 83 | |
| 84 | const isDuplicate = error.message.includes('already exists') |
| 85 | if (isDuplicate) { |
| 86 | return NextResponse.json({ error: 'Resource already exists' }, { status: 409 }) |
| 87 | } |
| 88 | } |
| 89 | |
| 90 | logger.error(`[${requestId}] ${defaultMessage}:`, error) |
| 91 | return NextResponse.json({ error: defaultMessage }, { status: 500 }) |
| 92 | } |