Course offer · HLD · LLD · System Design at ₹799 until 30 Nov (not interview packs)

Global Error Handling in JavaScript

Set up global error handling in JavaScript with window error and unhandledrejection events, Node process handlers and an error logger. Explanation and output.

IntermediateJavaScript Error 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}

Sample Output

// Nothing prints until an error happens.

The code only registers listeners. You need a real error to see the rest.

Global error: Uncaught ReferenceError: x is not defined

Browsers add the word Uncaught to event.message.

In this one

  • How the window error event catches uncaught errors
  • How unhandledrejection catches lost promise errors
  • How Node.js handles errors with process.on
  • How to wrap functions so errors get reported

How it works

  1. 1

    An error listener is added to window.

  2. 2

    An unhandledrejection listener is added.

  3. 3

    In Node, process handlers are added instead.

  4. 4

    An ErrorBoundary and an ErrorLogger are created.

  5. 5

    withErrorReporting is ready to wrap functions.

Edge cases

Scripts from other sites

The message is only "Script error." with no line number.

Load the script with crossorigin and send CORS headers.

Code after an uncaught exception

The Node app keeps running in a bad state.

Log the error and exit, then let a process manager restart it.

What's going on

Some errors slip past every try and catch. A global handler is the last safety net. It runs for errors that nobody else caught, so you can log them and keep users informed. JavaScript has global hooks in the browser and in Node.js.

In the browser, window.addEventListener('error', ...) runs when a script throws an uncaught error. The event gives you the message, the file name, the line number (lineno), the column number (colno) and the error object. Calling event.preventDefault() stops the browser from printing its own red error.

The unhandledrejection event is the same idea for promises. It fires when a promise rejects and nothing catches it. event.reason holds the error.

Method 3 is for Node.js, where there is no window. process.on('uncaughtException') catches thrown errors, and process.on('unhandledRejection') catches rejected promises. After an uncaught exception the program may be in a broken state, so the code exits with process.exit(1). Exit code 1 means the program failed.

Method 4 is a small error boundary that keeps a list of caught errors. Method 5 is a logger that adds the browser name (navigator.userAgent) and the page address (window.location.href), then sends the entry to a server.

Method 6, withErrorReporting, wraps any function. If the function throws, the wrapper reports the error and then throws it again.

This sample only sets up handlers. No error is triggered, so it prints nothing by itself. The output below shows what you would see after an error happens. It is browser code and fails in Node because window is missing.

Quiz

Tap an option. The answer stays hidden until you pick.

Question 1

Which event catches a rejected promise with no catch?

Pick an answer to check it.

Question 2

What does process.exit(1) mean?

Pick an answer to check it.

Questions people ask

Does a global handler replace try and catch?

No. It is a last safety net. Handle expected errors close to where they happen.

Why call preventDefault in unhandledrejection?

It stops the browser from printing its own warning.

Why does this code fail in Node?

window and navigator only exist in the browser.