|
| 1 | +/** |
| 2 | + * Next.js Instrumentation |
| 3 | + * |
| 4 | + * This file runs once when the server starts and sets up global error handlers |
| 5 | + * to catch unhandled promise rejections and uncaught exceptions. |
| 6 | + * |
| 7 | + * Without these handlers, unhandled errors can crash the Node.js process, |
| 8 | + * causing Render's proxy to return 502 Bad Gateway errors. |
| 9 | + */ |
| 10 | + |
| 11 | +import { logger } from '@/util/logger' |
| 12 | + |
| 13 | +export function register() { |
| 14 | + // Handle unhandled promise rejections (async errors that aren't caught) |
| 15 | + process.on( |
| 16 | + 'unhandledRejection', |
| 17 | + (reason: unknown, promise: Promise<unknown>) => { |
| 18 | + logger.error( |
| 19 | + { |
| 20 | + reason: |
| 21 | + reason instanceof Error |
| 22 | + ? { message: reason.message, stack: reason.stack } |
| 23 | + : reason, |
| 24 | + promise: String(promise), |
| 25 | + }, |
| 26 | + '[CRITICAL] Unhandled Promise Rejection', |
| 27 | + ) |
| 28 | + // Don't exit - let the process continue to handle other requests |
| 29 | + // In production, Render will restart if there's a real crash |
| 30 | + }, |
| 31 | + ) |
| 32 | + |
| 33 | + // Handle uncaught exceptions (sync errors that aren't caught) |
| 34 | + process.on('uncaughtException', (error: Error, origin: string) => { |
| 35 | + logger.error( |
| 36 | + { |
| 37 | + message: error.message, |
| 38 | + stack: error.stack, |
| 39 | + origin, |
| 40 | + }, |
| 41 | + '[CRITICAL] Uncaught Exception', |
| 42 | + ) |
| 43 | + // Don't exit - let the process continue to handle other requests |
| 44 | + // This prevents a single bad request from taking down the entire server |
| 45 | + }) |
| 46 | + |
| 47 | + logger.info({}, '[Instrumentation] Global error handlers registered') |
| 48 | +} |
0 commit comments