From 2dff0620c1cc5169ee62e0ce1451f988e94ec738 Mon Sep 17 00:00:00 2001 From: Trevor Dixon Date: Fri, 13 Jun 2025 08:44:08 +0200 Subject: [PATCH] Catch execution errors and pass them to onError and renderError if provided --- source/components/JsxParser.test.tsx | 13 +++++++++++++ source/components/JsxParser.tsx | 11 ++++++++++- 2 files changed, 23 insertions(+), 1 deletion(-) diff --git a/source/components/JsxParser.test.tsx b/source/components/JsxParser.test.tsx index 5fdaa5d..1b69453 100644 --- a/source/components/JsxParser.test.tsx +++ b/source/components/JsxParser.test.tsx @@ -1038,6 +1038,19 @@ describe('JsxParser Component', () => { expect(() => render( { throw e }} />)).toThrow() expect(() => render( { throw e }} />)).toThrow() }) + + test('renderError catches errors', () => { + const renderError = jest.fn((...args) => console.error(...args)) + render( + , + ) + expect(renderError).toHaveBeenCalledWith({ error: 'Error: Test error' }) + }) + test('supports className prop', () => { const { node } = render() expect(node.classList.contains('foo')).toBeTruthy() diff --git a/source/components/JsxParser.tsx b/source/components/JsxParser.tsx index 165a3bd..1c31b33 100644 --- a/source/components/JsxParser.tsx +++ b/source/components/JsxParser.tsx @@ -133,7 +133,16 @@ export default class JsxParser extends React.Component { return null } - return parsed.map(p => this.#parseExpression(p)).filter(Boolean) + try { + return parsed.map(p => this.#parseExpression(p)).filter(Boolean) + } catch (error) { + if (this.props.showWarnings) console.warn(error) // eslint-disable-line no-console + if (this.props.onError) this.props.onError(error as Error) + if (this.props.renderError) { + return this.props.renderError({ error: String(error) }) + } + throw error + } } /**