Node.js: Keep operation and cleanup failures in one report
A failed write followed by a failed close needs both errors in the diagnostic report. A cleanup failure that replaces the write error can hide the original fault.
Set up
Tested on Debian 13 Linux with Node.js v24.22.1. Use Bash, Node.js on your PATH, a text editor, and the mktemp, rm and rmdir utilities. No packages or network access are needed. Keep the same terminal through cleanup. Stop if setup fails before saving the source.
start_dir="$PWD"
work_dir="$(mktemp -d)" || exit 1
cd -- "$work_dir" || exit 1Run the example
Save as node-preserve-operation-cleanup-errors.mjs:
import assert from 'node:assert/strict';
async function runAndClean(run, cleanup) {
let value;
let failed = false;
let operationError;
try {
value = await run();
} catch (error) {
failed = true;
operationError = error;
}
try {
await cleanup();
} catch (cleanupError) {
if (failed) {
throw new AggregateError(
[operationError, cleanupError],
'Operation and cleanup failed',
);
}
throw cleanupError;
}
if (failed) throw operationError;
return value;
}
const operationError = new Error('write failed');
const cleanupError = new Error('close failed');
const failOperation = async () => { throw operationError; };
const failCleanup = async () => { throw cleanupError; };
const succeed = async () => 'saved';
assert.equal(await runAndClean(succeed, succeed), 'saved');
await assert.rejects(runAndClean(failOperation, succeed), (e) => e === operationError);
await assert.rejects(runAndClean(succeed, failCleanup), (e) => e === cleanupError);
await assert.rejects(runAndClean(failOperation, failCleanup), (error) => {
assert.ok(error instanceof AggregateError);
assert.deepEqual(error.errors, [operationError, cleanupError]);
console.log(error.errors.map((item) => item.message).join(' | '));
return true;
});
await assert.rejects(runAndClean(() => { throw undefined; }, failCleanup), (error) => {
assert.deepEqual(error.errors, [undefined, cleanupError]);
return true;
});
console.log('success, single failures, and undefined rejection: passed');Run:
node node-preserve-operation-cleanup-errors.mjsObserved output:
write failed | close failed
success, single failures, and undefined rejection: passedRead the result
The helper runs cleanup after the operation settles. If only one step fails, it throws that original value. If both fail, the errors array retains the operation failure first and the cleanup failure second. A separate boolean tracks failure because JavaScript can throw undefined; checking whether the saved error is truthy would lose that case.
Apply it carefully
The callbacks model write and close failures without touching files. Supply a cleanup callback only for a resource that was successfully acquired, or make it safe for partial initialization. The helper cannot force either callback to settle, undo a partial write or make cleanup succeed. Handle or report the AggregateError at the caller, and avoid logging sensitive payloads from errors.
The ECMAScript AggregateError constructor stores the supplied failure values. This helper’s ordering and single-failure policy are application choices.
Clean up
Remove the saved file and empty scratch directory. If the directory is not empty, inspect its contents before removing anything else.
rm -- node-preserve-operation-cleanup-errors.mjs
cd -- "$start_dir" || exit 1
rmdir -- "$work_dir"
unset start_dir work_dirAcknowledgements
This post was created with assistance from AI.