Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
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, and error reporting strategies.
Global Error Handlers
Global error handlers allow you to catch and handle errors that occur during the runtime of your JavaScript application. By utilizing 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);
};
// Trigger an error to see the handler in action
setTimeout(() => {
throw new Error("Test error for demonstration");
}, 1000);
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: Test error for demonstration URL: about:blank Line: 12 Column: 10 Error object: Error: Test error for demonstration
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
function someFunction() {
throw new TypeError("someFunction is not implemented");
}
try {
// Code that might throw an error
const result = someFunction();
console.log("Result:", result);
} catch (error) {
console.error("An error occurred:", error.message);
console.log("Continuing execution after error handling...");
}
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: someFunction is not implemented Continuing execution after error handling...
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 message:", error.message);
console.error("Stack trace:");
console.error(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 message: Something went wrong
Stack trace:
Error: Something went wrong
at bar (<anonymous>:6:10)
at foo (<anonymous>:2:4)
at <anonymous>:10:4
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
import * as Sentry from "@sentry/browser";
Sentry.init({
dsn: 'your-sentry-dsn',
environment: 'production',
// Other configuration options
});
try {
// Code that might throw an error
riskyOperation();
} catch (error) {
// Send error to Sentry with additional context
Sentry.captureException(error, {
tags: {
component: 'user-profile'
},
extra: {
userId: getCurrentUserId()
}
});
}
Explanation
The code initializes 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 with additional context information.
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 to manage.
Example
class ValidationError extends Error {
constructor(message, field) {
super(message);
this.name = "ValidationError";
this.field = field;
}
}
class NetworkError extends Error {
constructor(message, statusCode) {
super(message);
this.name = "NetworkError";
this.statusCode = statusCode;
}
}
try {
throw new ValidationError("Email is required", "email");
} catch (error) {
console.error("Error type:", error.name);
console.error("Error message:", error.message);
console.error("Field:", error.field);
}
try {
throw new NetworkError("Server unavailable", 503);
} catch (error) {
console.error("Network error:", error.message);
console.error("Status code:", error.statusCode);
}
Explanation
The code defines custom error classes ValidationError and NetworkError that extend the built-in Error class. Each custom error includes additional properties specific to its use case. In the try blocks, instances of these custom errors are thrown with specific error messages and custom properties. The catch blocks log the custom properties of the caught error objects.
Output
Error type: ValidationError Error message: Email is required Field: email Network error: Server unavailable Status code: 503
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
class ErrorReporter {
static async sendErrorNotification(error, severity = 'medium') {
const errorData = {
message: error.message,
stack: error.stack,
timestamp: new Date().toISOString(),
userAgent: navigator.userAgent,
url: window.location.href,
severity: severity
};
// Send to multiple channels based on severity
if (severity === 'critical') {
await this.sendSlackAlert(errorData);
await this.sendEmailAlert(errorData);
} else {
await this.logToService(errorData);
}
}
static async sendSlackAlert(errorData) {
// Implementation for Slack webhook
console.log('Sending Slack alert:', errorData.message);
}
static async sendEmailAlert(errorData) {
// Implementation for email notification
console.log('Sending email alert:', errorData.message);
}
static async logToService(errorData) {
// Implementation for logging service
console.log('Logging to service:', errorData.message);
}
}
try {
// Simulate critical error
throw new Error("Database connection failed");
} catch (error) {
ErrorReporter.sendErrorNotification(error, 'critical');
}
Explanation
The code defines an ErrorReporter class that handles error notifications based on severity levels. The sendErrorNotification() method collects error context and routes notifications to appropriate channels. Critical errors trigger both Slack and email alerts, while medium-severity errors are logged to a service. This approach allows for proactive notification and response to errors, helping facilitate timely troubleshooting and resolution.
Comparison of Error Handling Approaches
| Approach | Scope | Best For | Limitations |
|---|---|---|---|
| Global Error Handlers | Application-wide | Catching unexpected errors | Less control over specific errors |
| Try/Catch Blocks | Code block specific | Handling known error scenarios | Must wrap each risky operation |
| Custom Error Classes | Application-specific | Domain-specific error handling | Requires upfront design |
| Logging Libraries | Application-wide | Production error tracking | External dependency, cost |
Conclusion
Effective error monitoring and logging are essential for maintaining robust JavaScript applications. Combine global error handlers for unexpected issues, try/catch blocks for known risks, and logging libraries for production monitoring. Custom error classes and notification systems further enhance your error handling strategy.
