Error Monitoring and Logging Techniques in JavaScript


JavaScript error monitoring and logging are crucial for maintaining the stability and performance of your applications. In this article, we will explore advanced techniques that can help you effectively monitor and log errors in your JavaScript code. We'll cover global error handlers, try/catch blocks, stack traces, logging libraries, custom error classes, error reporting and notifications, and error tracking in production.

Global Error Handlers

Global error handlers allow you to catch and handle errors that occur during the runtime of your JavaScript application. By utilising window.onerror and window.onunhandledrejection, you can log or report errors and exceptions.

Example

window.onerror = function(message, url, line, column, error) {
   console.error("An error occurred:", message);
   console.error("URL:", url);
   console.error("Line:", line);
   console.error("Column:", column);
   console.error("Error object:", error);
};

window.onunhandledrejection = function(event) {
   console.error("Unhandled promise rejection:", event.reason);
};

Explanation

The provided code sets up global error handlers in JavaScript. window.onerror captures unhandled errors and logs the error message, script URL, line and column numbers, and the error object. window.onunhandledrejection captures unhandled promise rejections and logs the rejection reason. These handlers help in identifying and logging errors that occur during the runtime of a web page.

Output

An error occurred: ReferenceError: someVariable is not defined
URL: https://example.com/js/app.js
Line: 42
Column: 15
Error object: ReferenceError: someVariable is not defined

Try/Catch Blocks

Using try/catch blocks allows you to handle specific exceptions and gracefully recover from errors that might occur within a block of code.

Example

try {
   // Code that might throw an error
   const result = someFunction();
   console.log("Result:", result);
} catch (error) {
   console.error("An error occurred:", error);
}

Explanation

The provided code uses a try/catch block to handle potential errors in JavaScript. The try block contains the code that might throw an error, and if an error occurs, the catch block is executed, which logs the error message using console.error().

Output

An error occurred: TypeError: someFunction is not a function

Stack Traces

Stack traces provide valuable information about the sequence of function calls leading to an error. They help in understanding the origin of the error and diagnosing the issue effectively.

Example

function foo() {
   bar();
}

function bar() {
   throw new Error("Something went wrong");
}

try {
   foo();
} catch (error) {
   console.error("Error stack trace:", error.stack);
}

Explanation

The code defines two functions, foo() and bar(). When foo() is called, it invokes bar(), which intentionally throws an error using throw new Error().

The code is wrapped in a try/catch block. When an error is thrown within the try block, it is caught by the catch block, and the error object is stored in the error variable.

The catch block logs the stack trace of the error using console.error() and the error.stack property.

Output

Error stack trace: Error: Something went wrong
   at bar (script.js:5:9)
   at foo (script.js:2:3)
   at script.js:10:3

Logging Libraries

Logging libraries like Sentry, Rollbar, and LogRocket provide advanced error monitoring features. They simplify error tracking, aggregation, and reporting, and often offer integrations with frameworks and services.

Example

// Using Sentry logging library
Sentry.init({
   dsn: 'your-sentry-dsn',
   // Other configuration options
});

try {
   // Code that might throw an error
} catch (error) {
   Sentry.captureException(error);
}

Explanation

The code initialises the Sentry logging library and sets up error capturing. Inside the try block, you can place the code that may throw an error, and if an error occurs, the catch block uses Sentry.captureException() to send the error to Sentry for logging and analysis.

Custom Error Classes

Extending the built-in Error class allows you to create custom error classes with additional properties and methods. This makes error handling more informative and easier.

Example

Consider the code shown below.

class MyCustomError extends Error {
   constructor(message, customProperty) {
      super(message);
      this.customProperty = customProperty;
   }
}

try {
   throw new MyCustomError("Something went wrong.", "Custom data");
} catch (error) {
   console.error("Custom property:", error.customProperty);
}

Explanation

The code defines a custom error class MyCustomError that extends Error. Inside the try block, it throws an instance of MyCustomError with a specific error message and custom property. In the catch block, it logs the custom property of the caught error object.

Output

Custom property: Custom data

Error Reporting and Notifications

Integrate your error monitoring system with notification services like email or chat platforms to receive real-time alerts when critical errors occur.

Example

Consider the code shown below.

function sendErrorNotification(error) {
   // Code to send an error notification via email or chat
}

try {
   // Code that might throw an error
} catch (error) {
   sendErrorNotification(error);
}

Explanation

The code defines a function sendErrorNotification() that takes an error parameter and contains the logic to send an error notification, such as via email or chat.

Within the try block, you can place the code that may potentially throw an error. If an error occurs, the catch block is executed, and the sendErrorNotification() function is called with the error object as an argument, triggering the error notification process.

This code demonstrates how to handle errors by calling a custom function to send error notifications when an error occurs within the try block. It allows for proactive notification and response to errors, helping to facilitate timely troubleshooting and resolution.

Conclusion

Effective error monitoring and logging techniques are vital for maintaining the stability and performance of your JavaScript applications. By leveraging global error handlers, try/catch blocks, stack traces, logging libraries, custom error classes, error reporting and notifications, and error tracking in production, you can detect, diagnose, and resolve issues more efficiently. Remember to strike a balance between logging detail and data sensitivity, and regularly review your logs for proactive maintenance and improvements in your applications.

Updated on: 25-Jul-2023

90 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements