Log error to console with Web Workers in HTML5

Web Workers in HTML5 provide a way to run JavaScript in the background without blocking the main thread. When working with Web Workers, proper error handling is crucial for debugging and maintaining application stability.

Error Handling with worker.onerror

The worker.onerror event handler catches errors that occur within the Web Worker and allows you to log them to the console for debugging purposes.

Example

Here's a complete example showing how to implement error handling in Web Workers:

<!DOCTYPE HTML>
<html>
    <head>
        <title>Web Worker Error Handling</title>
        <script>
            var worker = new Worker('bigLoop.js');
            
            // Handle successful messages from worker
            worker.onmessage = function (event) {
                alert("Completed " + event.data + " iterations");
            };
            
            // Handle errors from worker
            worker.onerror = function (event) {
                console.log("Worker error:", event.message);
                console.log("Error details:", event);
                console.log("File:", event.filename);
                console.log("Line:", event.lineno);
            };
            
            function sayHello() {
                alert("Hello sir....");
            }
            
            function startWorker() {
                worker.postMessage("start");
            }
        </script>
    </head>
    <body>
        <input type="button" onclick="sayHello();" value="Say Hello"/>
        <input type="button" onclick="startWorker();" value="Start Worker"/>
    </body>
</html>

Worker File (bigLoop.js)

Here's an example of the corresponding worker file that might generate errors:

// bigLoop.js
onmessage = function(event) {
    try {
        var iterations = 0;
        
        // Simulate a big loop that might cause errors
        for (var i = 0; i 

Error Object Properties

The error event object provides several useful properties for debugging:

Property Description
message Error message text
filename Name of the worker file where error occurred
lineno Line number where the error occurred

Best Practices

When implementing Web Worker error handling:

  • Always include an onerror handler to catch unexpected errors
  • Log comprehensive error information including filename and line number
  • Use try-catch blocks within the worker for controlled error handling
  • Consider sending error messages back to the main thread via postMessage for custom error handling

Conclusion

Implementing proper error handling in Web Workers using worker.onerror helps maintain application stability and provides valuable debugging information. Always log error details to the console for effective troubleshooting.

Updated on: 2026-03-15T23:18:59+05:30

709 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements