Global Error Handling
Handle errors globally
IntermediateTopic: Error Handling
JavaScript Global Error Handling Program
This program helps you to learn the fundamental structure and syntax of JavaScript programming.
// Method 1: Window error handler
window.addEventListener('error', function(event) {
console.error('Global error:', event.message);
console.error('File:', event.filename);
console.error('Line:', event.lineno);
console.error('Column:', event.colno);
console.error('Error:', event.error);
// Send to error tracking service
// logErrorToService(event);
// Prevent default browser error handling
// return true;
});
// Method 2: Unhandled promise rejection
window.addEventListener('unhandledrejection', function(event) {
console.error('Unhandled promise rejection:', event.reason);
event.preventDefault(); // Prevent default handling
});
// Method 3: Node.js error handling
if (typeof process !== 'undefined') {
process.on('uncaughtException', (error) => {
console.error('Uncaught exception:', error);
// Graceful shutdown
process.exit(1);
});
process.on('unhandledRejection', (reason, promise) => {
console.error('Unhandled rejection:', reason);
});
}
// Method 4: Error boundary (React-like)
class ErrorBoundary {
constructor() {
this.errors = [];
}
catchError(error, errorInfo) {
this.errors.push({ error, errorInfo, timestamp: Date.now() });
console.error('Error caught:', error, errorInfo);
}
getErrors() {
return this.errors;
}
}
const errorBoundary = new ErrorBoundary();
// Method 5: Error logging service
class ErrorLogger {
constructor() {
this.errors = [];
}
log(error, context = {}) {
const errorEntry = {
message: error.message,
stack: error.stack,
context: context,
timestamp: new Date().toISOString(),
userAgent: navigator.userAgent,
url: window.location.href
};
this.errors.push(errorEntry);
// Send to server
this.sendToServer(errorEntry);
}
sendToServer(errorEntry) {
// fetch('/api/errors', { method: 'POST', body: JSON.stringify(errorEntry) });
console.log('Error logged:', errorEntry);
}
}
const errorLogger = new ErrorLogger();
// Method 6: Error reporting
function reportError(error, context) {
errorLogger.log(error, context);
}
// Wrap functions with error reporting
function withErrorReporting(fn) {
return function(...args) {
try {
return fn.apply(this, args);
} catch (error) {
reportError(error, { function: fn.name, args });
throw error;
}
};
}Output
Global error: ReferenceError: x is not defined
File: script.js
Line: 10
Column: 5
Error: ReferenceError: x is not defined
Unhandled promise rejection: Error: Promise rejected
Error caught: Error Error info
Error logged: { message: "...", stack: "...", context: {...}, timestamp: "...", userAgent: "...", url: "..." }Understanding Global Error Handling
Global error handling catches all errors.
Window Error Handler
•Catches all errors
•Access error details
•Log to service
•Prevent default
Unhandled Rejections
•Promise rejections
•Handle globally
•Prevent crashes
Node.js Handlers
•uncaughtException
•unhandledRejection
•Graceful shutdown
Error Logging
•Centralized logging
•Include context
•Send to server
•Track errors
Error Reporting
•Report to service
•Include metadata
•User context
•Stack traces
Best Practices
•Set up early
•Log properly
•Don't crash app
•Monitor errors
Let us now understand every line and the components of the above program.
Note: To write and run JavaScript programs, you need to set up the local environment on your computer. Refer to the complete article Setting up JavaScript Development Environment. If you do not want to set up the local environment on your computer, you can also use online IDE to write and run your JavaScript programs.