Throwing at a Validation Boundary
Validate input where it enters your code and throw a descriptive Error, so bad values can't silently propagate deeper into the program.
if (!valid) throw new Error('description');
Purpose
A validation boundary is the point where external or untrusted input (a function argument, a
parsed API response, user input) first enters code that assumes it’s already correct. Throwing a
descriptive Error there — rather than letting a bad value silently continue — stops a small
problem from becoming a confusing failure somewhere else entirely.
Example
function withdraw(balance, amount) {
if (amount <= 0) {
throw new Error('Withdrawal amount must be positive.');
}
if (amount > balance) {
throw new Error('Insufficient funds.');
}
return balance - amount;
}
try {
withdraw(100, -5);
} catch (error) {
console.log(error.message); // "Withdrawal amount must be positive."
}
Behavior notes
new Error('message')creates anErrorobject with a.messageand a.stack(the trace at the point it was created). Built-in subclasses (TypeError,RangeError, and others) exist for more specific cases; a customclass MyError extends Error {}is also common once error handling needs to distinguish categories programmatically.- The function that throws doesn’t decide how the error is handled — the caller does, via
try/catcharound the call. This separates “detecting a problem” from “deciding what to do about it.” - Validating at the boundary means the rest of the function’s body can assume its inputs are already valid, rather than re-checking throughout.
Common mistakes
- Validating deep inside a call chain instead of at the boundary where bad data first entered — makes the eventual error harder to trace back to its real cause.
- Throwing a generic
Error('Invalid input')with no detail about what was invalid — a message that includes the actual bad value and what was expected saves significant debugging time later.
Runtime notes
A coding pattern built on core ECMAScript throw/try/catch, behaving identically anywhere
JavaScript runs.