From 6ba11d308b723ae731f877f69230c2f7a0701dea Mon Sep 17 00:00:00 2001 From: Arthur Vivian Date: Fri, 17 Mar 2023 15:11:02 +0000 Subject: [PATCH] Handle error response code when loading .riv files --- js/src/rive.ts | 14 +++++++++++--- js/test/rive.test.ts | 29 +++++++++++++++++++++++++++++ 2 files changed, 40 insertions(+), 3 deletions(-) diff --git a/js/src/rive.ts b/js/src/rive.ts index 977f4eed..b8a746e0 100644 --- a/js/src/rive.ts +++ b/js/src/rive.ts @@ -1193,7 +1193,12 @@ export class Rive { ): Promise { // Load the buffer from the src if provided if (this.src) { - this.buffer = await loadRiveFile(this.src); + try { + this.buffer = await loadRiveFile(this.src); + } catch (e) { + this.eventManager.fire({ type: EventType.LoadError, data: e.message }); + return Promise.reject(e.message); + } } // Load the Rive file this.file = await this.runtime.load(new Uint8Array(this.buffer)); @@ -1920,8 +1925,11 @@ interface RiveFileContents { const loadRiveFile = async (src: string): Promise => { const req = new Request(src); const res = await fetch(req); - const buffer = await res.arrayBuffer(); - return buffer; + if (res.status < 400) { + const buffer = await res.arrayBuffer(); + return buffer; + } + throw new Error(`Error loading ${src}: ${res.status} ${res.statusText}`); }; // #endregion diff --git a/js/test/rive.test.ts b/js/test/rive.test.ts index 16d248d4..34a10361 100644 --- a/js/test/rive.test.ts +++ b/js/test/rive.test.ts @@ -1163,3 +1163,32 @@ test("Rive deletes instances on the cleanup", (done) => { }); // #endregion + +// #region error handling + +test("Rive triggers onLoadError if the request to load the .riv fails", (done) => { + global.fetch = jest + .fn() + .mockImplementation(() => + Promise.resolve( + new Response("", { status: 404, statusText: "Not Found" }) + ) + ); + + const canvas = document.createElement("canvas"); + + new rive.Rive({ + canvas: canvas, + src: "a/file.riv", + autoplay: true, + artboard: "MyArtboard", + onLoadError: () => { + // @ts-ignore + global.fetch.mockClear(); + delete global.fetch; + done(); + }, + }); +}); + +// #endregion