Error Handling in JavaScript
Use exceptions to signal failures; catch them where you can recover and let them bubble otherwise.
Throwing and Error types
throw new Error('oops')
throw new TypeError('bad type')
throw new RangeError('out of range')
Custom errors extend Error.
class NotFound extends Error {}
try / catch / finally
try {
risky()
} catch (e) {
console.error(e.message)
console.error(e.stack)
} finally {
cleanup()
}
Modern JS allows catch { ... } without a binding name.
Promise rejections
Handle with .catch() or try/catch around await.
async function main() {
try { await doAsync() } catch (e) { /* ... */ }
}
Listen for global unhandled rejections to log and fail tests.
Error boundaries (UI)
In React and similar frameworks, use error boundaries to catch render errors.
Summary
- Throw
Error(or subclasses) for exceptional conditions - Use
try/catch/finally; handle promise rejections - Log stack traces; add boundaries in UIs