diff --git a/src/vision.ts b/src/vision.ts index 895094b..7849d2e 100644 --- a/src/vision.ts +++ b/src/vision.ts @@ -12,16 +12,31 @@ export class Vision { */ ocr(path: string): AbortablePromise { let worker: any; + let reject: (err: any) => void; + + const handler = (err: Error) => { + if(err.stack?.includes('tesseract.js')) { + process.off('uncaughtException', handler); + reject?.(err); + return; + } + throw err; + }; + process.on('uncaughtException', handler); + const p = (async () => { worker = await createWorker(this.ai.options.ocr || 'eng', 2, {cachePath: this.ai.options.path}); - worker.setParameters({}).catch(() => {}); // force error handler attachment return await new Promise((res, rej) => { - worker.on?.('error', rej); // catch worker-level throws + reject = rej; worker.recognize(path) .then(({data}: any) => res(data.text.trim() || null)) .catch(rej); }); - })().finally(() => worker?.terminate()); + })().finally(() => { + process.off('uncaughtException', handler); + worker?.terminate(); + }); + return Object.assign(p, {abort: () => worker?.terminate()}); } }