Parse Node.js Unhandled Promise Rejection
Parse Node.js UnhandledPromiseRejectionWarning stack traces. Extract async error context, file paths, and the rejected promise chain from Node.js applications.
Detailed Explanation
Understanding Node.js Unhandled Promise Rejections
An UnhandledPromiseRejectionWarning occurs when a Promise is rejected but no .catch() handler or try/catch in an async function is present to handle the error. Starting from Node.js 15, unhandled rejections terminate the process by default.
Stack Trace Format
UnhandledPromiseRejectionWarning: Error: Connection refused
at TCPConnectWrap.afterConnect [as oncomplete] (net.js:1141:16)
at Protocol._enqueue (/app/node_modules/mysql/lib/protocol/Protocol.js:144:48)
at Connection.query (/app/node_modules/mysql/lib/Connection.js:198:25)
at DatabaseService.findUser (/app/src/services/database.ts:87:12)
at UserController.getUser (/app/src/controllers/user.ts:34:20)
Async Stack Trace Challenges
Promise-based code creates asynchronous boundaries that can break the stack trace chain. Before Node.js 12 added --async-stack-traces, you might see a truncated trace that only shows the rejection point, not the full async call chain. Modern Node.js (16+) provides much better async stack traces by default.
Key Differences from Synchronous Errors
- The error may be thrown inside a
.then()callback or anasyncfunction - The stack trace might include internal Node.js event loop frames (
processTicksAndRejections,asyncRunEntryPoint) - Multiple unhandled rejections can fire from the same root cause if errors propagate through parallel promises
Prevention Strategies
- Always add
.catch()to promise chains - Use
try/catchin everyasyncfunction - Add a global handler:
process.on('unhandledRejection', handler) - Use ESLint rules like
no-floating-promisesto catch missing handlers at compile time
Use Case
Unhandled promise rejections are a critical issue in Node.js production servers because they can crash the process. Operations teams monitoring error logs need to quickly identify the source of the rejection and whether it stems from a database connection, API call, or file system operation. Parsing these traces helps prioritize fixes based on which service is affected.