Learn the concept
Error Handling
try/catch wraps code that might throw errors: the try block runs the code, catch handles any error that occurs, and the optional finally block always executes regardless of the outcome. Use it for operations that can fail at runtime like API calls, JSON parsing, and user input processing.
Error handling prevents your application from crashing when unexpected things happen.
Syntax:
try {
// code that might throw
} catch (error) {
// handle the error
} finally {
// always runs (optional)
}The error object has properties:
error.message — human-readable descriptionerror.name — error type (TypeError, ReferenceError, etc.)error.stack — call stack traceCommon error types:
TypeError — wrong type (e.g., calling non-function)ReferenceError — undefined variableSyntaxError — invalid codeRangeError — value out of rangeWhen to use:
// Basic usage
try {
const data = JSON.parse('{invalid json}');
} catch (error) {
console.error('Parse failed:', error.message);
// SyntaxError with message about invalid JSON
} finally {
console.log('This always runs');
}
// Throwing custom errors
function divide(a, b) {
if (b === 0) {
throw new Error('Cannot divide by zero');
}
return a / b;
}
try {
const result = divide(10, 0);
} catch (error) {
console.error(error.message); // 'Cannot divide by zero'
}Catching fetch failures, HTTP errors, and JSON parsing errors with appropriate user feedback
Throwing and catching custom validation errors for invalid user input before submission
Providing fallback behavior when optional features or third-party services fail at runtime
Build a fetch wrapper with automatic retry logic and exponential backoff for failed requests
Build an error tracking utility that captures, categorizes, and reports application errors with stack traces
Real-time error tracking and performance monitoring that automatically captures uncaught JavaScript exceptions
Error-handling middleware with (err, req, res, next) signature provides centralized error handling for Node.js web applications