Global Error Handling in JavaScript

Handle errors globally

IntermediateError HandlingExample 5 of 10
global-error-handling.js
1// Method 1: Window error handler
2window.addEventListener('error', function(event) {
3 console.error('Global error:', event.message);
4 console.error('File:', event.filename);
5 console.error('Line:', event.lineno);
6 console.error('Column:', event.colno);
7 console.error('Error:', event.error);
8
9 // Send to error tracking service
10 // logErrorToService(event);
11
12 // Prevent default browser error handling
13 // return true;
14});
15
16// Method 2: Unhandled promise rejection
17window.addEventListener('unhandledrejection', function(event) {
18 console.error('Unhandled promise rejection:', event.reason);
19 event.preventDefault(); // Prevent default handling
20});
21
22// Method 3: Node.js error handling
23if (typeof process !== 'undefined') {
24 process.on('uncaughtException', (error) => {
25 console.error('Uncaught exception:', error);
26 // Graceful shutdown
27 process.exit(1);
28 });
29
30 process.on('unhandledRejection', (reason, promise) => {
31 console.error('Unhandled rejection:', reason);
32 });
33}
34
35// Method 4: Error boundary (React-like)
36class ErrorBoundary {
37 constructor() {
38 this.errors = [];
39 }
40
41 catchError(error, errorInfo) {
42 this.errors.push({ error, errorInfo, timestamp: Date.now() });
43 console.error('Error caught:', error, errorInfo);
44 }
45
46 getErrors() {
47 return this.errors;
48 }
49}
50
51const errorBoundary = new ErrorBoundary();
52
53// Method 5: Error logging service
54class ErrorLogger {
55 constructor() {
56 this.errors = [];
57 }
58
59 log(error, context = {}) {
60 const errorEntry = {
61 message: error.message,
62 stack: error.stack,
63 context: context,
64 timestamp: new Date().toISOString(),
65 userAgent: navigator.userAgent,
66 url: window.location.href
67 };
68
69 this.errors.push(errorEntry);
70 // Send to server
71 this.sendToServer(errorEntry);
72 }
73
74 sendToServer(errorEntry) {
75 // fetch('/api/errors', { method: 'POST', body: JSON.stringify(errorEntry) });
76 console.log('Error logged:', errorEntry);
77 }
78}
79
80const errorLogger = new ErrorLogger();
81
82// Method 6: Error reporting
83function reportError(error, context) {
84 errorLogger.log(error, context);
85}
86
87// Wrap functions with error reporting
88function withErrorReporting(fn) {
89 return function(...args) {
90 try {
91 return fn.apply(this, args);
92 } catch (error) {
93 reportError(error, { function: fn.name, args });
94 throw error;
95 }
96 };
97}

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: "..." }

What's going on

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