Handling Errors in Error-First Callbacks
What you'll learn: The three common patterns for responding to errors in error-first callbacks: logging, rethrowing, or recovering.
The Core Idea
Once you've checked for an error in an error-first callback (that first parameter), you need to decide what to do with it. You have three main strategies:
- Log it — Record the error and continue (or stop)
- Rethrow it — Pass the error up to a higher-level handler
- Recover from it — Handle the error gracefully and provide a fallback
Think of these like handling a package delivery problem: you can write down what went wrong (log), send it back to the warehouse (rethrow), or accept a substitute item (recover).
The Three Patterns
Logging
function readConfig(callback) {
readFile('config.json', (err, data) => {
if (err) {
console.error('Failed to read config:', err.message);
return callback(err); // Still pass it up
}
callback(null, data);
});
}
Rethrowing
function fetchUser(id, callback) {
getFromDatabase(id, (err, user) => {
if (err) {
// Wrap and rethrow with more context
const newErr = new Error(`User ${id} fetch failed`);
return callback(newErr);
}
callback(null, user);
});
}
Recovering
function loadSettings(callback) {
readFile('settings.json', (err, data) => {
if (err) {
// Provide default settings instead
const defaults = { theme: 'light', lang: 'en' };
return callback(null, defaults);
}
callback(null, data);
});
}
Key Takeaway: When handling errors in error-first callbacks, choose whether to log and propagate, rethrow with added context, or recover gracefully with fallback values—never ignore the error silently.