An operation was attempted on a resource that has been closed.
Production Risk
Medium. This indicates a state management problem that could lead to unexpected crashes or resource leaks if not handled correctly.
This error is thrown when an attempt is made to use a resource after its `close()` method has been called. This is common with resources that manage an underlying handle, like a file descriptor or a network socket. Once closed, the resource is no longer usable, and any further operations are invalid.
- 1Attempting to interact with an `fs.FSWatcher` after calling its `.close()` method.
- 2Using an HTTP/2 session or stream object after it has been closed.
- 3A race condition where one part of the code closes a resource while another part is about to use it.
This error occurs when a method is called on an object that has an internal 'closed' state flag set to true.
const fs = require('fs');
const watcher = fs.watch(__filename);
watcher.close();
try {
// Attempting to add another listener after closing.
watcher.on('change', () => {});
} catch (err) {
console.error(err.code);
}expected output
ERR_USE_AFTER_CLOSE
Fix
Ensure Resource is Open
WHEN Interacting with a closeable resource.
const fs = require('fs');
const watcher = fs.watch(__filename);
let isClosed = false;
watcher.on('close', () => {
isClosed = true;
});
// Sometime later...
if (!isClosed) {
// It's safe to interact with the watcher.
}Why this works
Structure your code to ensure that operations on a resource only happen between its creation and the emission of its 'close' event. Avoid sharing closeable resources across complex asynchronous flows where their state is uncertain.
const fs = require('fs');
const watcher = fs.watch(__filename);
watcher.close();
try { // this triggers ERR_USE_AFTER_CLOSEtry {
// operation that may throw ERR_USE_AFTER_CLOSE
riskyOperation()
} catch (err) {
if (err.code === 'ERR_USE_AFTER_CLOSE') {
console.error('ERR_USE_AFTER_CLOSE:', err.message)
} else {
throw err
}
}// Validate inputs before calling the operation
function safe_err_use_after_close(...args) {
// validate args here
return performOperation(...args)
}✕
Content generated with AI assistance and reviewed for accuracy. Found an error? hello@errcodes.dev