refactor: refine worker message handling error messsage
[poolifier.git] / src / worker / abstract-worker.ts
index 493ca0b293fc145b2eae812f0e0dd858b9b4e566..6bf84b875622ebaece3d8b4b8dae3c637593ed68 100644 (file)
@@ -301,7 +301,9 @@ export abstract class AbstractWorker<
     if (this.isMain) {
       throw new Error('Cannot handle message to worker in main worker')
     } else if (message.workerId != null && message.workerId !== this.id) {
-      throw new Error('Message worker id does not match the worker id')
+      throw new Error(
+        `Message worker id ${message.workerId} does not match the worker id ${this.id}`
+      )
     } else if (message.workerId === this.id) {
       if (message.statistics != null) {
         // Statistics message received
@@ -328,12 +330,27 @@ export abstract class AbstractWorker<
     this.stopCheckActive()
     if (isAsyncFunction(this.opts.killHandler)) {
       (this.opts.killHandler?.() as Promise<void>)
-        .then(() => this.emitDestroy())
+        .then(() => {
+          this.sendToMainWorker({ kill: 'success', workerId: this.id })
+          return null
+        })
+        .catch(() => {
+          this.sendToMainWorker({ kill: 'failure', workerId: this.id })
+        })
+        .finally(() => {
+          this.emitDestroy()
+        })
         .catch(EMPTY_FUNCTION)
     } else {
-      // eslint-disable-next-line @typescript-eslint/no-invalid-void-type
-      this.opts.killHandler?.() as void
-      this.emitDestroy()
+      try {
+        // eslint-disable-next-line @typescript-eslint/no-invalid-void-type
+        this.opts.killHandler?.() as void
+        this.sendToMainWorker({ kill: 'success', workerId: this.id })
+      } catch {
+        this.sendToMainWorker({ kill: 'failure', workerId: this.id })
+      } finally {
+        this.emitDestroy()
+      }
     }
   }