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
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
onerrorhandler to catch unexpected errors - Log comprehensive error information including filename and line number
- Use
try-catchblocks within the worker for controlled error handling - Consider sending error messages back to the main thread via
postMessagefor 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.
