Choosing the Right Error Strategy
You'll learn: How to decide between throw, returning errors, or callbacks based on your function's design and caller expectations.
What's at Stake?
Error handling isn't one-size-fits-all. The method you choose—throwing exceptions, returning error objects, or using error-first callbacks—affects how easy your code is to use, maintain, and integrate with other systems.
Think of it like choosing a delivery method for bad news: sometimes you shout across the room (throw), sometimes you hand someone a note (return error), and sometimes you call them with the news (callbacks).
The Three Main Strategies
throw for exceptional conditions: Use when something truly unexpected happens that the immediate caller probably can't handle. Best for synchronous code and operations that should succeed under normal circumstances.
function withdraw(amount) {
if (amount < 0) throw new RangeError('Amount must be positive');
// withdrawal logic
}
Return errors for expected failures: When errors are part of normal operation—like validation failures or "not found" scenarios—return an error object or result type. The caller explicitly checks for failure.
function findUser(id) {
const user = database.get(id);
if (!user) return { error: 'User not found' };
return { data: user };
}
Error-first callbacks for async operations: In callback-based APIs, pass errors as the first argument. This pattern signals "check for errors before using results."
fs.readFile('config.json', (err, data) => {
if (err) return console.error(err);
// use data
});
Making the Choice
- Sync + exceptional:
throw - Expected failures + explicit handling: return errors
- Async + callback-based: error-first callbacks
- Async + modern: use promises/async-await with try/catch
Key Takeaway: Choose throw for unexpected errors in sync code, return error objects when failures are predictable and part of normal flow, and use error-first callbacks for traditional async APIs—align your strategy with caller expectations.