Sobes.tech
Middle

How do you track and monitor errors in JavaScript?

sobes.tech AI

Answer from AI

Errors in JavaScript are tracked and monitored using the following methods:

  • Browser console: The main debugging tool during development. Error messages (synthetic, logical, runtime) are displayed with file and line number.

  • try...catch blocks: Catch runtime errors, allowing handling or additional information display.

    try {
      // Code that may cause an error
      let result = riskyOperation();
    } catch (error) {
      // Error handling
      console.error("An error occurred:", error.message);
      // You can send the error to the server
      sendErrorToServer(error);
    }
    
  • window.onerror: Global handler for unhandled JavaScript errors. Allows centralized catching of errors that "slip through" try...catch.

    window.onerror = function(message, source, lineno, colno, error) {
      console.error("Global error:", message, source, lineno, colno);
      // Sending error information to the server
      sendErrorToServer({
        message: message,
        source: source,
        lineno: lineno,
        colno: colno,
        stack: error ? error.stack : 'N/A'
      });
      return true; // Return true to suppress the default error display in the console
    };
    
  • unhandledrejection event for Promises: Catches unhandled errors in promises.

    window.addEventListener('unhandledrejection', function(event) {
      console.error('Unhandled Promise Rejection:', event.reason);
      // Sending error information to the server
      sendErrorToServer(event.reason);
    });
    
  • Error monitoring systems (Sentry, Bugsnag, Rollbar): Professional services that collect, aggregate, and analyze errors in real-time. They provide stack traces, user environment info, error frequency, and notifications. They are main tools in production.

  • Server-side logging: Errors caught on the frontend with try...catch, onerror, or unhandledrejection are sent to the server for centralized storage and analysis.

The method choice depends on the development stage and error criticality. In production, I always use a combination of try...catch, global handlers, and monitoring systems.