Fix UnhandledPromiseRejection Errors in Node.js
Fix UnhandledPromiseRejection errors in Node.js 24 by finding the floating promise, awaiting or catching it, and setting a safe process-level handler.

Since Node.js 15 the default response to a promise that rejects with no handler is to crash the process. In Node.js 24 you see a message that names the error and ends with an exit code of 1, and on older versions you saw only a deprecation warning. The crash feels sudden because the failing code often ran moments earlier and the stack trace points at the original error, not at the line that forgot to handle it. This post shows what the error looks like, the four common causes and how to fix each one, and what to put in a process-level handler so a missed case logs cleanly instead of killing the server. The examples run on Node.js 24.
The error
A minimal program that triggers it:
async function loadConfig() {
throw new Error("config file missing");
}
loadConfig(); // returns a rejected promise nobody handles
console.log("started");started
file:///crash.mjs:2
throw new Error("config file missing");
^
Error: config file missing
at loadConfig (file:///crash.mjs:2:9)
at file:///crash.mjs:5:1
at ModuleJob.run (node:internal/modules/esm/module_job:271:25)
Node.js v24.0.0The path, line numbers and internal frames differ on your machine. The program printed started, then the rejection was detected after the current tick and the process exited with code 1. When the rejection reason is not an Error, such as a plain string, the message is longer and reads [UnhandledPromiseRejection: This error originated either by throwing inside of an async function without a catch block, or by rejecting a promise which was not handled with .catch(). The promise rejected with the reason "..."] with the code ERR_UNHANDLED_REJECTION. That wording is the actual text people search for.
Cause 1: a missing await
The most common cause is calling an async function and not awaiting it.
async function save() {
throw new Error("write failed");
}
async function handler() {
try {
save(); // not awaited, so the catch below cannot see it
} catch (error) {
console.log("caught:", error.message);
}
}
await handler();The try/catch is useless here, because the error happens later, after handler has moved on. The fix is await save():
async function save() {
throw new Error("write failed");
}
async function handler() {
try {
await save();
} catch (error) {
console.log("caught:", error.message);
}
}
await handler();caught: write failedCause 2: a promise created and dropped
Sometimes the promise is created in a place where you cannot await, such as an event handler or a constructor. If the work is truly fire-and-forget, attach a .catch() so failure is logged on purpose.
async function sendMetrics() {
throw new Error("metrics service unreachable");
}
sendMetrics().catch((error) => console.log("metrics failed:", error.message));metrics failed: metrics service unreachableA good habit is to wrap that in a helper named for what it does, such as background(promise), which logs and swallows the error, so a reader sees at once that dropping the result is deliberate.
Cause 3: async callbacks passed to APIs that ignore promises
Methods such as forEach, event emitters and setTimeout call your function and discard its return value. If the function is async and throws, the rejected promise it returned has no handler.
import { EventEmitter } from "node:events";
const emitter = new EventEmitter();
emitter.on("job", async () => {
try {
throw new Error("job failed");
} catch (error) {
console.log("handled inside:", error.message);
}
});
emitter.emit("job");handled inside: job failedPut the try/catch inside the async callback, since nobody outside can catch for you. For forEach, use for...of with await or Promise.all(items.map(...)). For event emitters, EventEmitter accepts the option captureRejections: true, which routes a rejected promise from a handler to the error event, or to a Symbol.for("nodejs.rejection") method, instead of crashing.
Cause 4: a promise chain with no end
A chain that ends without .catch or an await leaves any failure unhandled, and a .then placed after a .catch can fail too.
Promise.resolve()
.then(() => {
throw new Error("step failed");
})
.catch((error) => console.log("caught:", error.message))
.then(() => {
throw new Error("cleanup failed"); // nothing after this to catch it
});The first error is handled, and the second is not, so the process exits. Add a final .catch, or convert the chain to async/await with a try/catch.
Find the origin when the trace is unhelpful
When the rejection comes from deep inside a library, the stack shows where the error was created but not where you forgot a handler. Two tools help. Run with node --trace-uncaught app.mjs to print the stack where the error was thrown. And register a handler that logs the promise and reason, which also gives you a place to attach context.
process.on("unhandledRejection", (reason, promise) => {
console.error("Unhandled rejection:", reason instanceof Error ? reason.message : reason);
process.exitCode = 1;
});
Promise.reject(new Error("example failure"));
await new Promise((resolve) => setTimeout(resolve, 10));
console.log("still running");Unhandled rejection: example failure
still runningWith a handler registered, Node.js does not crash by default, and the program continued. That is a safety net, not a fix, and treating it as one hides real bugs.
What the process handler should do
A server that has hit an unhandled rejection is in an unknown state: some operation failed and nobody cleaned up after it. The safest policy for most services is to log the error with full context, then exit and let the process manager restart a clean process. The alternative, continuing, is reasonable only when you know the failed work was isolated. Node.js also lets you choose the behavior with the --unhandled-rejections flag: throw is the default, strict raises it as an uncaught exception without waiting, warn logs and continues, warn-with-error-code logs and sets the exit code, and none silences it. Use warn modes only as a temporary bridge while you fix the offenders.
Prevent it with tooling
Add the lint rule @typescript-eslint/no-floating-promises to catch the first two causes at edit time, and @typescript-eslint/no-misused-promises to catch the third. Both need type information, so enable the project service in your ESLint config. In tests, the built-in test runner fails a test with an unhandled rejection, which turns many production crashes into red builds.
Where the advice stops
Do not silence the error globally to make a log quieter. A handler that does nothing converts a visible crash into silent data loss. Also remember that a rejection handled late, for example attached after an await, can still be reported as unhandled first, because Node.js checks after the microtask queue drains. Attach handlers in the same tick as the promise is created, or use Promise.all and await patterns that attach them immediately.
A checklist for a crash report
When a crash with this error arrives from production, work through the same short list each time. Read the first line of the stack to learn what failed, not who forgot to handle it. Search the code around the top frames for a call to an async function that lacks await, return or .catch. Check whether the failing call sits inside a callback passed to a method that ignores promises: forEach, setTimeout, an event listener, an Array.prototype.map whose result is never awaited. Look at recent changes, since a function that used to be synchronous and became async is the classic way a once-safe call turns into a floating promise.
Then fix the cause rather than the symptom. The lowest-risk change is usually adding the missing await and a try/catch that does something useful with the error: retry, fall back, return a clear status to the caller or log with enough context to debug it. Add a test that makes the dependency fail and asserts the new behavior, so the same mistake cannot come back unnoticed in a later refactor.
Containers and process managers
In production the crash is only half the story, because what happens next depends on how the process is supervised. Under a process manager or a container orchestrator, a crash with exit code 1 is followed by a restart, and a loop of crashes shows up as a crash loop with backoff. Make sure in-flight requests are not lost without notice: a graceful shutdown handler that stops accepting new connections and lets existing ones finish is worth having, even though in a real unhandled-rejection case the process may be in no condition to finish anything. Logging the error synchronously before exit, to a destination that survives the process, makes the difference between a crash you can diagnose and one you can only count.


