Proper error handling for OCR
Some checks failed
Publish Library / Tag Version (push) Has been cancelled
Publish Library / Build NPM Project (push) Has been cancelled

This commit is contained in:
2026-06-09 11:20:50 -04:00
parent 4ac3036000
commit 710c6ce52c

View File

@@ -12,16 +12,31 @@ export class Vision {
*/ */
ocr(path: string): AbortablePromise<string | null> { ocr(path: string): AbortablePromise<string | null> {
let worker: any; 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 () => { const p = (async () => {
worker = await createWorker(this.ai.options.ocr || 'eng', 2, {cachePath: this.ai.options.path}); 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<string | null>((res, rej) => { return await new Promise<string | null>((res, rej) => {
worker.on?.('error', rej); // catch worker-level throws reject = rej;
worker.recognize(path) worker.recognize(path)
.then(({data}: any) => res(data.text.trim() || null)) .then(({data}: any) => res(data.text.trim() || null))
.catch(rej); .catch(rej);
}); });
})().finally(() => worker?.terminate()); })().finally(() => {
process.off('uncaughtException', handler);
worker?.terminate();
});
return Object.assign(p, {abort: () => worker?.terminate()}); return Object.assign(p, {abort: () => worker?.terminate()});
} }
} }