Skip to main content

Command Palette

Search for a command to run...

Frontend Error Monitoring and Log Collection Practices

Updated
3 min read
Frontend Error Monitoring and Log Collection Practices

Frontend error monitoring and log collection are critical for ensuring application stability and enhancing user experience. This document explores commonly used methods for frontend error monitoring and log collection.

Using try-catch for Error Handling

Wrap potentially error-prone code in a try-catch block to capture errors:

try {
  // Code that might throw an error
} catch (error) {
  // Handle the caught error
  console.error('An error occurred:', error);
  // Report error to backend logging service
  reportErrorToBackend(error);
}

In the reportErrorToBackend function, use libraries like fetch or axios to send error details to the server.

Using the Browser’s window.onerror Event

A global error handler can capture uncaught errors:

window.onerror = function(errorMessage, fileName, lineNumber, columnNumber, error) {
  // Log error details
  console.error(errorMessage, fileName, lineNumber, columnNumber, error);
  // Send to backend
  reportErrorToBackend(errorMessage, fileName, lineNumber, columnNumber, error);
  // Return true to prevent default browser behavior
  return true;
};

Using Third-Party Libraries like TrackJS

TrackJS provides an automated way to collect and analyze errors:

<script src="https://cdn.trackjs.com/track.js"></script>
<script>
TrackJS.configure({
  token: 'your_token_here',
  application: 'your_application_name',
});
</script>

Using Error Boundary in React

For React applications, Error Boundaries can capture and handle errors within components:

class ErrorBoundary extends React.Component {
  constructor(props) {
    super(props);
    this.state = { hasError: false, errorInfo: null };
  }

  static getDerivedStateFromError(error) {
    return { hasError: true };
  }

  componentDidCatch(error, errorInfo) {
    // Log error
    reportErrorToBackend(error, errorInfo);
  }

  render() {
    if (this.state.hasError) {
      return <h1>Something went wrong.</h1>;
    }
    return this.props.children; // Normally, re-render children
  }
}

// Wrap potentially error-prone components
<ErrorBoundary>
  <MyComponentThatMayThrow />
</ErrorBoundary>

Using Vue.js Error Handling

Vue.js supports both global and component-level error handling:

// Global error handling
Vue.config.errorHandler = function(error, instance, info) {
  console.error(error, instance, info);
  reportErrorToBackend(error, info);
};

// Component-level error handling
export default {
  created() {
    this.$onErrorCapture = (error, instance, info) => {
      console.error(error, instance, info);
      reportErrorToBackend(error, info);
    };
  },
};

Using Angular’s ErrorHandler

Angular provides an ErrorHandler service for global error handling:

import { ErrorHandler, Injectable } from '@angular/core';

@Injectable()
export class CustomErrorHandler implements ErrorHandler {
  handleError(error) {
    console.error('An error occurred:', error);
    reportErrorToBackend(error);
  }
}

Register the error handler in AppModule:

@NgModule({
  providers: [{ provide: ErrorHandler, useClass: CustomErrorHandler }],
  // ...
})
export class AppModule {}

Using Sentry

Sentry is a popular error tracking service offering detailed error reports, context, and stack traces:

<script src="https://browser.sentry-cdn.com/5.16.4/minimal@sentry.io/dist/sentry.min.js"
  crossorigin="anonymous"></script>
<script>
Sentry.init({
  dsn: 'your_sentry_dsn',
  release: 'your_app@version',
  integrations: [new Sentry.Integrations.BrowserTracing()],
  tracesSampleRate: 0.5, // Adjust sampling rate
});
</script>

Using LogRocket

LogRocket provides user session recording and error tracking:

<script>
!function(LR){var t;t=document.createElement("script"),
t.setAttribute("src","https://logs-01.logrocket.io/ln.js?projectid=your_project_id"),
t.setAttribute("data-logrocket","true"),t.setAttribute("async","true"),
document.body.appendChild(t)}();
</script>

Using Loggly

Loggly is a cloud-based log management service:

<script src="https://js.loggly.com/inputs/your_loggly_key.js" async></script>
<script>
logglyTracker.push(['log', 'An error occurred', { error: errorObject }]);
</script>

Local Log Files

You can log errors locally and periodically upload them to a server, useful in offline environments or when avoiding real-time reporting:

function writeLocalLogFile(error) {
  const timestamp = new Date().toISOString();
  const logEntry = `${timestamp}: ${JSON.stringify(error)}`;
  localStorage.setItem('errorLog', (localStorage.getItem('errorLog') || '') + '\n' + logEntry);
}

// Usage
try {
  // Your code
} catch (error) {
  writeLocalLogFile(error);
  reportErrorToBackend(error); // If network available, send
}

Client-Side Error Reporting

Enhance user experience by adding a feedback mechanism, allowing users to choose whether to report errors:

function showReportErrorDialog(error) {
  const dialogResult = confirm('Do you want to report this error?');
  if (dialogResult) {
    reportErrorToBackend(error);
  }
}

try {
  // Your code
} catch (error) {
  showReportErrorDialog(error);
}

Web Development

Part 8 of 46

The content covers the three basics of HTML/CSS/JS/TS, modular development, mainstream frameworks (Vue, React, Angular, Svelte), build tools, browser plug-in development, Node.js backend practice, Next.js/Nest.js and other popular technologies.

Up next

Deep Dive into Vue.js Component Communication Methods

Vue.js component communication is achieved through several methods, each suited to specific use cases. Below is a comprehensive overview of these methods, including code examples and their characteristics. Props Direction: Parent to Child Purpose: ...

More from this blog

T

Tianya School Technical Articles

48 posts

Welcome to our tech publication, where we share high-quality content on full-stack development, frontend/backend/web3/AI, and engineering best practices.