Best Practices for Throwing Errors
You'll learn how to throw errors effectively by following conventions that make debugging easier and code more maintainable.
Core Principles
When you throw errors, you're communicating with future developers (including yourself). Good error practices make problems easier to diagnose and fix.
Think of error messages like road signs: they should be clear, specific, and point you in the right direction. A vague sign saying "Problem ahead" isn't as helpful as "Bridge out 2 miles ahead—detour left."
Error Message Conventions
Be specific and actionable:
// Bad: vague and unhelpful
throw new Error('Invalid input');
// Good: specific and actionable
throw new TypeError('Expected name to be a string, got number');
Include context:
function withdraw(amount, balance) {
if (amount > balance) {
throw new RangeError(
`Insufficient funds: attempted to withdraw ${amount}, but balance is ${balance}`
);
}
}
Choose the Right Error Type
Match the error type to the problem:
// Type problems
throw new TypeError('callback must be a function');
// Range/value problems
throw new RangeError('age must be between 0 and 120');
// General logic errors
throw new Error('Cannot process order: cart is empty');
Preserve Stack Traces
When rethrowing or wrapping errors, preserve the original stack trace:
try {
riskyOperation();
} catch (err) {
// Good: wraps but preserves original error
throw new Error(`Failed to complete operation: ${err.message}`);
}
Key Takeaway: Use specific error types, write clear descriptive messages with context, and always consider what information will help someone debug the problem quickly.