From 760a6cbfe16dd94741404f5cdcd4fd773931d174 Mon Sep 17 00:00:00 2001 From: Cesar Augusto Date: Fri, 25 Oct 2024 11:15:24 -0300 Subject: [PATCH] Add better error handling Only call onComplete if all files were successfully uploaded --- package.json | 1 + src/extensions/FileUploadExtension.ts | 25 ++++++++++++++++--------- 2 files changed, 17 insertions(+), 9 deletions(-) diff --git a/package.json b/package.json index 97bd67b..7f8dcc7 100644 --- a/package.json +++ b/package.json @@ -43,6 +43,7 @@ "eslint-plugin-prettier": "^5.2.1", "globals": "^15.9.0", "happy-dom": "^15.0.0", + "msw": "^2.5.1", "prettier": "^3.3.3", "rollup-plugin-peer-deps-external": "^2.2.4", "rollup-plugin-visualizer": "^5.12.0", diff --git a/src/extensions/FileUploadExtension.ts b/src/extensions/FileUploadExtension.ts index 647443c..39c43bb 100644 --- a/src/extensions/FileUploadExtension.ts +++ b/src/extensions/FileUploadExtension.ts @@ -27,6 +27,7 @@ export interface FileUploadOptions { onDrop: (currentEditor: Editor, file: File, pos: number) => void onStart: (currentEditor: Editor) => void onUpload: (currentEditor: Editor, file: UploadTask) => void + onUploadError: (currentEditor: Editor, file: UploadTask) => void onComplete: (currentEditor: Editor, files: UploadTask[]) => void } @@ -57,6 +58,7 @@ export const FileUploadExtension = Extension.create({ onDrop() {}, onStart() {}, onUpload() {}, + onUploadError() {}, onComplete() {}, } }, @@ -102,12 +104,21 @@ export const FileUploadExtension = Extension.create({ uploader.selectFiles() tr.setMeta('selectFiles', null) } else if (tr.getMeta('uploadFiles')) { + let hasErrors = false + this.storage.files = [] this.options.onStart(this.editor) for await (const file of uploader.uploadFiles()) { this.storage.files.push(file) - this.options.onUpload(this.editor, file) + if ('error' in file) { + hasErrors = true + this.options.onUploadError(this.editor, file) + } else { + this.options.onUpload(this.editor, file) + } + } + if (!hasErrors) { + this.options.onComplete(this.editor, this.storage.files) } - this.options.onComplete(this.editor, this.storage.files) tr.setMeta('uploadFiles', null) } }) @@ -209,7 +220,7 @@ class Uploader { } catch (error) { const msg = error as string this.onUploadDone(node, { error: msg }) - throw new Error(msg as string) + return { error: msg } } } @@ -217,12 +228,8 @@ class Uploader { const tasks = this.findNodes(false).map(([node, pos]) => { return this.upload(node, pos) }) - try { - for await (const res of tasks) { - yield res - } - } catch (error) { - console.error(error) + for await (const res of tasks) { + yield res } }