Sub topic 8
When Cleanup Fails: SuppressedError
Cleanup code can fail too. A file handle may refuse to close, a network connection may already be gone, or a lock release may hit a bug. With manual try/finally, an exception thrown in finally silently replaces the exception from try, and the original error is lost. The using and await using declarations keep both errors. They do this with a built-in error type called SuppressedError.
This chapter assumes you know try/catch/finally semantics, the using and await using declarations, and the rule that resources are disposed in reverse order of declaration. The examples run in runtimes that ship explicit resource management natively, such as Node.js 24 and recent Chromium-based browsers.
The problem SuppressedError solves
Here is the error-loss bug in plain try/finally:
function manual() {
try {
throw new Error("body failed");
} finally {
throw new Error("cleanup failed");
}
}
try {
manual();
} catch (e) {
console.log(e.message); // "cleanup failed"
// "body failed" is gone: nothing references it any more
}The body error is usually the one you need for debugging, because it says what actually went wrong. The cleanup error is often just a consequence of it. For example, closing a connection fails because the query had already broken the connection. Losing the first error makes the second one hard to interpret.
The basic case: body and cleanup both throw
When a using block exits because of an exception and a disposer then throws as well, the runtime throws a SuppressedError that holds both errors:
try {
using res = {
[Symbol.dispose]() {
throw new Error("cleanup failed");
},
};
throw new Error("body failed");
} catch (e) {
console.log(e instanceof SuppressedError); // true
console.log(e.error.message); // "cleanup failed"
console.log(e.suppressed.message); // "body failed"
}The two properties are easy to mix up:
| Property | Holds | Meaning |
|---|---|---|
| `error` | The error thrown by the disposer | The newer error, the one that "won" |
| `suppressed` | The error that was already propagating | The older error, which would otherwise have been lost |
| `message` | A string | Engine-supplied or empty. Don't rely on its text |
| `name` | `"SuppressedError"` | Inherited from the prototype |
A useful way to remember it: error is what was thrown just now, and suppressed is what it pushed aside. This is the same thing try/finally does, except the pushed-aside error is kept.
When no SuppressedError is created
A SuppressedError appears only when an error is already propagating and another one is added on top of it. In every other case the runtime throws a plain error or nothing:
| Block outcome | Disposer outcome | What the caller sees |
|---|---|---|
| Completes or returns normally | All succeed | The normal result |
| Throws `E` | All succeed | `E`, unchanged |
| Completes or returns normally | One throws `D` | `D`, unchanged, not wrapped |
| Throws `E` | One throws `D` | `SuppressedError { error: D, suppressed: E }` |
| Completes normally | Two throw, `D1` first, then `D2` | `SuppressedError { error: D2, suppressed: D1 }` |
The third row has a consequence that is easy to overlook. A failing disposer replaces a successful return value:
function failing(name) {
return {
[Symbol.dispose]() {
throw new Error(`${name} cleanup failed`);
},
};
}
function compute() {
using r = failing("r");
return 42;
}
try {
console.log(compute());
} catch (e) {
console.log(e instanceof SuppressedError); // false
console.log(e.message); // "r cleanup failed"
}The function computed 42, but the caller never receives it. This matches try/finally, where a throw in finally overrides a return in try. It is still a reason to think carefully before letting a disposer throw.
Chains: several resources failing
Disposal runs in reverse declaration order. Each failing disposer wraps whatever error is already propagating at that moment. With several failures you get a nested chain, and the outermost error is the last disposer that ran, which belongs to the first resource declared.
function failing(name) {
return {
[Symbol.dispose]() {
throw new Error(`${name} cleanup failed`);
},
};
}
try {
using a = failing("a");
using b = failing("b");
throw new Error("body failed");
} catch (e) {
console.log(e.error.message); // "a cleanup failed"
console.log(e.suppressed.error.message); // "b cleanup failed"
console.log(e.suppressed.suppressed.message); // "body failed"
}A failing disposer never stops the other disposers from running. Every registered resource still gets its dispose call, and the only effect of a failure is that the chain grows by one level. This is the main safety guarantee of the feature. One bad cleanup can't leak the other resources.
The original error sits at the bottom of the chain, under .suppressed.suppressed.... The chain grows deeper toward the oldest error.
Errors during declaration
A using initializer can throw too. Suppose using b = openB() throws after a was already bound. Then b never exists, a is disposed, and if a's disposer also throws you get SuppressedError { error: aError, suppressed: openBError }. To the runtime, an initializer error is just one more error that was already propagating when disposal started.
The same rules with await using
await using follows exactly the same rules. A rejected promise returned from Symbol.asyncDispose counts as a thrown disposal error:
async function main() {
try {
await using conn = {
async [Symbol.asyncDispose]() {
throw new Error("close failed");
},
};
throw new Error("query failed");
} catch (e) {
console.log(e instanceof SuppressedError); // true
console.log(e.error.message); // "close failed"
console.log(e.suppressed.message); // "query failed"
}
}
main();When a block mixes using and await using, disposal still runs in one reverse-order sequence, and a single error chain is built across both kinds.
Flattening a chain for logging and handling
Deeply nested properties are awkward to read and to match on. A small helper turns a chain into a flat array:
function flattenSuppressed(err) {
const errors = [];
let current = err;
while (current instanceof SuppressedError) {
errors.push(current.error);
current = current.suppressed;
}
errors.push(current);
return errors; // newest first, original error last
}
function failing(name) {
return {
[Symbol.dispose]() {
throw new Error(`${name} cleanup failed`);
},
};
}
try {
using a = failing("a");
using b = failing("b");
throw new Error("body failed");
} catch (e) {
for (const item of flattenSuppressed(e)) {
console.log(item.message);
}
// a cleanup failed
// b cleanup failed
// body failed
}The last element is the error that started the failure, so it is usually the one to report as the primary cause. There is one edge case. If a disposer's own error is itself a SuppressedError (because the disposer used using internally), the helper stops at that level and does not descend into it. Recurse into current.error if you need a full tree.
Error handling code that expects a specific type
Wrapping changes the type of the error that reaches your catch. Code like this stops working as soon as a disposer fails:
class NotFoundError extends Error {}
function handle(e) {
if (e instanceof NotFoundError) return "404";
return "500";
}A NotFoundError thrown inside a using block, followed by a failing disposer, arrives as a SuppressedError, so handle returns "500". A more tolerant check looks at the original error:
class NotFoundError extends Error {}
function rootCause(err) {
let current = err;
while (current instanceof SuppressedError) {
current = current.suppressed;
}
return current;
}
function handle(e) {
if (rootCause(e) instanceof NotFoundError) return "404";
return "500";
}
console.log(handle(new SuppressedError(new Error("close"), new NotFoundError("x"))));
// "404"Keep in mind that rootCause returns a disposal error when the body succeeded and only disposers failed (rows 3 and 5 of the table above). That is correct, because in that case the disposal error really is the first failure.
Constructing SuppressedError yourself
SuppressedError is a normal global constructor: new SuppressedError(error, suppressed, message). You rarely need it. It does make sense when you write your own cleanup helper and want its error reports to look like the built-in ones:
function closeAll(resources, primaryError) {
let pending = primaryError;
let hasError = primaryError !== undefined;
for (const r of [...resources].reverse()) {
try {
r.close();
} catch (e) {
pending = hasError ? new SuppressedError(e, pending, "close failed") : e;
hasError = true;
}
}
if (hasError) throw pending;
}
try {
closeAll(
[{ close() { throw new Error("x"); } }, { close() {} }],
new Error("primary")
);
} catch (e) {
console.log(e.error.message, "/", e.suppressed.message); // x / primary
}DisposableStack.prototype.dispose() and its async counterpart build chains in exactly this way, so code that inspects errors works the same whichever mechanism produced them.
Design advice: make disposers hard to break
SuppressedError keeps information from being lost. You still shouldn't need it often:
- Make disposers idempotent, so that a second call is a no-op instead of a "already closed" exception.
- For best-effort cleanup, such as deleting a temp file, catch and log inside the disposer instead of throwing.
- Throw from a disposer only when the failure means data may be lost, for example a failed flush or commit, so that callers need to know.
- Values thrown from disposers don't have to be
Errorobjects. A disposer that throws a string produces a chain containing a string. Always throwErrorinstances so that stack traces survive.
Exercise
In a block with using x = ...; using y = ...;, the body returns normally, x's disposer throws X, and y's disposer throws Y. What is thrown, and what are its error and suppressed properties?
Show answer
y is disposed first and throws Y. No error was propagating, so Y propagates unwrapped. Then x's disposer throws X while Y is propagating, so the result is a SuppressedError with error X and suppressed Y. The block's return value is discarded.
Exercise
A function contains using r = res; return compute();. compute() succeeds and r's disposer throws D. Does the caller receive a SuppressedError?
Show answer
No. No error was propagating when disposal ran, so D is thrown as-is and replaces the return value. A SuppressedError is created only when a disposal error lands on top of an error that is already propagating.
Exercise
Three resources a, b, c are declared in that order. The body throws E, and all three disposers throw (Da, Db, Dc). Write the property path from the caught error to E, and say which disposal error is at the top level.
Show answer
Disposal order is c, b, a, so the chain is SuppressedError(Da, SuppressedError(Db, SuppressedError(Dc, E))). The top-level error is Da, and E is at e.suppressed.suppressed.suppressed.