Error handling and unit tests
[poolifier.git] / lib / workers.js
index c192f1812c4a08cf8aa9cdc305a397c0740abdb5..0e8569e5423e3b91617d564e2a80cfde4c3aa45c 100644 (file)
@@ -27,9 +27,7 @@ class ThreadWorker extends AsyncResource {
       if (value && value.data && value._id) {
         // here you will receive messages
         // console.log('This is the main thread ' + isMainThread)
-        const res = this.runInAsyncScope(fn, null, value.data)
-        this.parent.postMessage({ data: res, _id: value._id })
-        this.lastTask = Date.now()
+        this._run(fn, value)
       } else if (value.parent) {
         // save the port to communicate with the main thread
         // this will be received once
@@ -47,6 +45,17 @@ class ThreadWorker extends AsyncResource {
       this.parent.postMessage({ kill: 1 })
     }
   }
+
+  _run (fn, value) {
+    try {
+      const res = this.runInAsyncScope(fn, null, value.data)
+      this.parent.postMessage({ data: res, _id: value._id })
+      this.lastTask = Date.now()
+    } catch (e) {
+      this.parent.postMessage({ error: e, _id: value._id })
+      this.lastTask = Date.now()
+    }
+  }
 }
 
 module.exports.ThreadWorker = ThreadWorker