From 49c86f3b3531bac5040f43ed52109ec9e1e642e7 Mon Sep 17 00:00:00 2001 From: pearmini Date: Tue, 5 Mar 2024 20:19:28 +0800 Subject: [PATCH] feat: handle error for promise and ob --- .../genji-theme-vitepress/__tests__/errors.md | 18 ++++++++++ packages/genji-theme-vitepress/src/render.js | 34 +++++++++---------- 2 files changed, 34 insertions(+), 18 deletions(-) diff --git a/packages/genji-theme-vitepress/__tests__/errors.md b/packages/genji-theme-vitepress/__tests__/errors.md index 357ae2d..ceef3b9 100644 --- a/packages/genji-theme-vitepress/__tests__/errors.md +++ b/packages/genji-theme-vitepress/__tests__/errors.md @@ -30,3 +30,21 @@ display(() => { return null; })(); ``` + +## Promise Error + +```js | dom +new Promise((resolve) => { + const a = 1; + a = 2; +}); +``` + +## Observable Error + +```js | dom +new Observable((observer) => { + const a = 1; + a = 2; +}); +``` diff --git a/packages/genji-theme-vitepress/src/render.js b/packages/genji-theme-vitepress/src/render.js index d5d5a48..3151ddf 100644 --- a/packages/genji-theme-vitepress/src/render.js +++ b/packages/genji-theme-vitepress/src/render.js @@ -89,7 +89,7 @@ function unmount(node) { function renderError(e, { script }) { const [error] = e.stack.split("\n"); - const node = document.createElement("div"); + const node = document.createElement("span"); node.classList.add("genji-error"); node.textContent = `${script}: ${error} (Open console for more details.)`; console.error(`${script}:`, e); @@ -144,6 +144,17 @@ function render(module, { isDark }) { const observable = new Observable((observer) => { let normalized; + + const next = (node) => { + normalized = normalize(node, { isDark }); + observer.next(normalized); + }; + + const error = (e) => { + normalized = renderError(e, { script }); + observer.error(normalized); + }; + try { const parsed = parseCode(code, P); @@ -153,30 +164,17 @@ function render(module, { isDark }) { `return value //# sourceURL=${script}` ) )(); - const next = (node) => { - normalized = normalize(node, { isDark }); - observer.next(normalized); - }; + if (node instanceof Promise) { next(renderLoading()); - node - .then((d) => next(d)) - .catch((e) => { - throw e; - }); + node.then(next).catch(error); } else if (node instanceof Observable) { - node.subscribe({ - next: (d) => next(d), - error: (e) => { - throw e; - }, - }); + node.subscribe({ next, error }); } else { next(node); } } catch (e) { - normalized = renderError(e, { script }); - observer.error(normalized); + error(e); } finally { return () => unmount(normalized); }