refactor: factor out WorkerError handling
authorJérôme Benoit <jerome.benoit@piment-noir.org>
Fri, 25 Oct 2024 15:21:56 +0000 (17:21 +0200)
committerJérôme Benoit <jerome.benoit@piment-noir.org>
Fri, 25 Oct 2024 15:21:56 +0000 (17:21 +0200)
Signed-off-by: Jérôme Benoit <jerome.benoit@piment-noir.org>
src/pools/abstract-pool.ts

index ce1ef3a3002ec13e03934056a735dc9eeeca6f87..77f7a23d5044ce76ba6fcb6e1c63563a283eff63 100644 (file)
@@ -10,6 +10,7 @@ import type {
   PromiseResponseWrapper,
   Task,
   TaskFunctionProperties,
+  WorkerError,
 } from '../utility-types.js'
 import type {
   TaskFunction,
@@ -1184,15 +1185,8 @@ export abstract class AbstractPool<
       const { asyncResource, reject, resolve, workerNodeKey } = promiseResponse
       const workerNode = this.workerNodes[workerNodeKey]
       if (workerError != null) {
-        let error: Error
-        if (workerError.error != null) {
-          error = workerError.error
-        } else {
-          const err = new Error(workerError.message)
-          err.stack = workerError.stack
-          error = err
-        }
         this.emitter?.emit(PoolEvents.taskError, workerError)
+        const error = this.handleWorkerError(workerError)
         asyncResource != null
           ? asyncResource.runInAsyncScope(reject, this.emitter, error)
           : reject(error)
@@ -1229,6 +1223,15 @@ export abstract class AbstractPool<
     }
   }
 
+  private handleWorkerError (workerError: WorkerError): Error {
+    if (workerError.error != null) {
+      return workerError.error
+    }
+    const error = new Error(workerError.message)
+    error.stack = workerError.stack
+    return error
+  }
+
   private handleWorkerReadyResponse (message: MessageValue<Response>): void {
     const { ready, taskFunctionsProperties, workerId } = message
     if (ready == null || !ready) {