From 66148956bc68271cc977ce72d7ab2da5a65ea355 Mon Sep 17 00:00:00 2001 From: William Candillon Date: Wed, 25 Nov 2026 08:42:33 +0000 Subject: [PATCH 1/3] =?UTF-8?q?feat(=F0=9F=9A=A8):=20add=20named=20Skia=20?= =?UTF-8?q?errors=20and=20raise=20them=20from=20native=20code?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit First step of the v3 error handling RFC: one family of named errors, modelled on WebGPU's error types, that every public API will throw or reject with. - SkiaError and its subclasses (SkiaDecodeError, SkSLCompilationError, SkiaValidationError, SkiaOutOfMemoryError, SkiaGPUUnavailableError, SkiaInternalError), plus the NotSupportedError, AbortError and NotFoundError names WebGPU uses, and isSkiaError() to recognize them by name on any runtime. - RNJsi::NamedError: a C++ exception that becomes the JS error of its name where it crosses into JS, in every host function the NativeObject installers create and in promises (executor, settle, reject). The JS errors are built with the constructors the package registers on the React Native runtime, so instanceof holds there; a worklet runtime gets an Error with the same name and extra field. - The web backend throws NotSupportedError for the APIs it does not have. - An Errors documentation page. No public API changes its behaviour yet: the factories and promises move to these errors in the following changes. --- apps/docs/docs/errors.md | 64 +++++++ apps/docs/sidebars.js | 5 + packages/skia/cpp/api/JsiSkNativeObjects.h | 32 ++-- packages/skia/cpp/jsi/JsiPromises.cpp | 13 +- packages/skia/cpp/jsi/JsiPromises.h | 3 + packages/skia/cpp/jsi/NamedError.h | 111 ++++++++++++ packages/skia/cpp/jsi/NativeObject.h | 91 ++++++---- packages/skia/cpp/rnskia/RNSkAsync.h | 4 + packages/skia/src/skia/NativeSetup.ts | 6 + .../skia/src/skia/__tests__/Errors.spec.ts | 74 ++++++++ packages/skia/src/skia/types/Errors.ts | 170 ++++++++++++++++++ packages/skia/src/skia/types/index.ts | 1 + packages/skia/src/skia/web/Host.ts | 6 +- 13 files changed, 526 insertions(+), 54 deletions(-) create mode 100644 apps/docs/docs/errors.md create mode 100644 packages/skia/cpp/jsi/NamedError.h create mode 100644 packages/skia/src/skia/__tests__/Errors.spec.ts create mode 100644 packages/skia/src/skia/types/Errors.ts diff --git a/apps/docs/docs/errors.md b/apps/docs/docs/errors.md new file mode 100644 index 0000000000..a209311efb --- /dev/null +++ b/apps/docs/docs/errors.md @@ -0,0 +1,64 @@ +--- +id: errors +title: Errors +sidebar_label: Errors +slug: /errors +--- + +React Native Skia reports failures the way WebGPU does: a call that fails throws an error with a name, a promise that fails rejects with one, and `null` is only ever a result, never a failure. + +## The rules + +| Situation | Outcome | +| --- | --- | +| A wrong argument type, a missing argument | Throws a `TypeError` | +| Data that cannot be decoded, parsed or compiled | Throws a `SkiaDecodeError` or an `SkSLCompilationError` | +| A GPU or CPU allocation that fails | Throws a `SkiaOutOfMemoryError` or a `SkiaValidationError` | +| No GPU on the device | Throws a `SkiaGPUUnavailableError` (see [`Skia.gpu`](/docs/webgpu#the-gpu-device)) | +| A valid call without a result (a path operation with an empty outcome, the end of an iteration) | Returns `null` | +| Asynchronous work that fails | Rejects with a named error | +| An API the platform does not have | Throws an error named `NotSupportedError` | + +## Error classes + +Every error React Native Skia raises extends `SkiaError`, which extends `Error`. + +| Class | Raised when | Extra field | +| --- | --- | --- | +| `SkiaDecodeError` | Bytes or text cannot be decoded: an image, an SVG, a font, a Lottie file, a picture, an SVG path string. | `format`: what was being decoded. | +| `SkSLCompilationError` | A shader fails to compile. | `messages`: the diagnostics, each with `type`, `message`, `lineNum` and `linePos`, like WebGPU's `GPUCompilationMessage`. | +| `SkiaValidationError` | A call is invalid in a way the types cannot catch: a surface of size zero, pixel data shorter than its image info. | | +| `SkiaOutOfMemoryError` | An allocation fails. | | +| `SkiaGPUUnavailableError` | The device has no GPU Skia can render with. The message is `Skia.gpu.error`. | | +| `SkiaInternalError` | Skia or the graphics driver fails on its own. | | + +Three more names follow the `DOMException` names WebGPU uses, as plain `SkiaError`s: `NotSupportedError`, `AbortError` and `NotFoundError`. + +## Handling errors + +```tsx +import { Skia, SkSLCompilationError } from "react-native-skia"; + +try { + const effect = Skia.RuntimeEffect.Make(source); +} catch (e) { + if (e instanceof SkSLCompilationError) { + for (const { lineNum, linePos, message } of e.messages) { + console.log(`${lineNum}:${linePos} ${message}`); + } + } +} +``` + +`instanceof` holds on the React Native runtime (and on the web). A worklet runtime receives errors that keep their `name`, message and extra field, but not their class. In code that may run in a worklet, check the name, or use `isSkiaError`: + +```tsx +import { isSkiaError } from "react-native-skia"; + +const onError = (e: unknown) => { + "worklet"; + if (isSkiaError(e, "AbortError")) { + // The GPU device was lost while the work was pending. + } +}; +``` diff --git a/apps/docs/sidebars.js b/apps/docs/sidebars.js index bdd0039752..0b3e7438cf 100644 --- a/apps/docs/sidebars.js +++ b/apps/docs/sidebars.js @@ -31,6 +31,11 @@ const sidebars = { label: "WebGPU", id: "webgpu", }, + { + type: "doc", + label: "Errors", + id: "errors", + }, { collapsed: true, type: "category", diff --git a/packages/skia/cpp/api/JsiSkNativeObjects.h b/packages/skia/cpp/api/JsiSkNativeObjects.h index 36f5aebd46..7f6202e96c 100644 --- a/packages/skia/cpp/api/JsiSkNativeObjects.h +++ b/packages/skia/cpp/api/JsiSkNativeObjects.h @@ -213,8 +213,10 @@ class JsiSkNativeObject : public RNJsi::NativeObject { runtime, jsi::PropNameID::forUtf8(runtime, name), 0, [method](jsi::Runtime &rt, const jsi::Value &thisValue, const jsi::Value *arguments, size_t count) -> jsi::Value { - auto native = fromThis(rt, thisValue); - return ((*native).*method)(rt, thisValue, arguments, count); + return RNJsi::guardNamedErrors(rt, [&]() -> jsi::Value { + auto native = fromThis(rt, thisValue); + return ((*native).*method)(rt, thisValue, arguments, count); + }); }); prototype.setProperty(runtime, name, func); } @@ -233,10 +235,12 @@ class JsiSkNativeObject : public RNJsi::NativeObject { runtime, jsi::PropNameID::forUtf8(runtime, name), sizeof...(Args), [method](jsi::Runtime &rt, const jsi::Value &thisValue, const jsi::Value *args, size_t count) -> jsi::Value { - auto native = fromThis(rt, thisValue); - invokeChainable(native.get(), method, rt, args, - std::index_sequence_for{}, count); - return jsi::Value(rt, thisValue); + return RNJsi::guardNamedErrors(rt, [&]() -> jsi::Value { + auto native = fromThis(rt, thisValue); + invokeChainable(native.get(), method, rt, args, + std::index_sequence_for{}, count); + return jsi::Value(rt, thisValue); + }); }); prototype.setProperty(runtime, name, func); } @@ -254,10 +258,13 @@ class JsiSkNativeObject : public RNJsi::NativeObject { runtime, jsi::PropNameID::forUtf8(runtime, name), sizeof...(Args), [method](jsi::Runtime &rt, const jsi::Value &thisValue, const jsi::Value *args, size_t count) -> jsi::Value { - auto native = fromThis(rt, thisValue); - invokeChainableWithRuntime(native.get(), method, rt, args, - std::index_sequence_for{}, count); - return jsi::Value(rt, thisValue); + return RNJsi::guardNamedErrors(rt, [&]() -> jsi::Value { + auto native = fromThis(rt, thisValue); + invokeChainableWithRuntime(native.get(), method, rt, args, + std::index_sequence_for{}, + count); + return jsi::Value(rt, thisValue); + }); }); prototype.setProperty(runtime, name, func); } @@ -279,9 +286,8 @@ class JsiSkNativeObject : public RNJsi::NativeObject { Derived *obj, ReturnType (Derived::*method)(jsi::Runtime &, Args...), jsi::Runtime &runtime, const jsi::Value *args, std::index_sequence, size_t count) { - (obj->*method)(runtime, - RNJsi::JSIConverter>::fromJSI( - runtime, args[Is], Is >= count)...); + (obj->*method)(runtime, RNJsi::JSIConverter>::fromJSI( + runtime, args[Is], Is >= count)...); } std::shared_ptr _context; diff --git a/packages/skia/cpp/jsi/JsiPromises.cpp b/packages/skia/cpp/jsi/JsiPromises.cpp index a15e01c96d..cbcf64a318 100644 --- a/packages/skia/cpp/jsi/JsiPromises.cpp +++ b/packages/skia/cpp/jsi/JsiPromises.cpp @@ -21,6 +21,10 @@ void JsiPromises::Promise::reject(const jsi::JSError &error) { reject_.call(runtime_, error.value()); } +void JsiPromises::Promise::reject(const NamedError &error) { + reject_.call(runtime_, error.toValue(runtime_)); +} + jsi::Value JsiPromises::createPromiseAsJSIValue(jsi::Runtime &rt, PromiseSetupFunctionType &&func) { @@ -33,8 +37,13 @@ JsiPromises::createPromiseAsJSIValue(jsi::Runtime &rt, jsi::Function reject = args[1].getObject(rt2).getFunction(rt2); auto wrapper = std::make_shared(rt2, std::move(resolve), std::move(reject)); - func(rt2, wrapper); - return jsi::Value::undefined(); + // A NamedError thrown before the work started rejects the promise + // with the error of its name (the Promise constructor turns the + // executor's exception into the rejection). + return guardNamedErrors(rt2, [&]() -> jsi::Value { + func(rt2, wrapper); + return jsi::Value::undefined(); + }); }); return JSPromise.callAsConstructor(rt, fn); diff --git a/packages/skia/cpp/jsi/JsiPromises.h b/packages/skia/cpp/jsi/JsiPromises.h index a89be59c08..77a971d2e8 100644 --- a/packages/skia/cpp/jsi/JsiPromises.h +++ b/packages/skia/cpp/jsi/JsiPromises.h @@ -7,6 +7,7 @@ #include #include "api/third_party/base64.h" +#include "jsi/NamedError.h" namespace RNJsi { namespace jsi = facebook::jsi; @@ -37,6 +38,8 @@ class JsiPromises { void reject(const std::string &error); /** Rejects with the JS error `error` carries, as thrown. */ void reject(const jsi::JSError &error); + /** Rejects with the JS error of the name `error` carries. */ + void reject(const NamedError &error); jsi::Runtime &runtime_; jsi::Function resolve_; diff --git a/packages/skia/cpp/jsi/NamedError.h b/packages/skia/cpp/jsi/NamedError.h new file mode 100644 index 0000000000..7f0bf56e55 --- /dev/null +++ b/packages/skia/cpp/jsi/NamedError.h @@ -0,0 +1,111 @@ +#pragma once + +#include +#include +#include +#include + +#include + +namespace RNJsi { + +namespace jsi = facebook::jsi; + +/** + A failure that reaches JS as an error of a given name: a SkiaDecodeError, + an AbortError, a TypeError. Native code throws it anywhere, on any thread; + it becomes a JS error where it crosses into JS (a host function, see + guardNamedErrors, or a promise, see JsiPromises::Promise::reject). + + The JS error is built by the constructor registered for its name in the + global `__RNSkiaErrors` (see src/skia/types/Errors.ts), so `instanceof` + holds on the runtime that registered them. A runtime without the registry + (a worklet runtime) gets an Error with the same name, message and extra + field. + */ +class NamedError : public std::runtime_error { +public: + /** Builds the value of the error's extra field on the runtime. */ + using Extra = std::function; + + NamedError(std::string name, const std::string &message) + : std::runtime_error(message), _name(std::move(name)) {} + + /** + An error that carries one more field, named `extraKey` (the `format` of a + SkiaDecodeError, the `messages` of an SkSLCompilationError). + */ + NamedError(std::string name, const std::string &message, std::string extraKey, + Extra extra) + : std::runtime_error(message), _name(std::move(name)), + _extraKey(std::move(extraKey)), _extra(std::move(extra)) {} + + const std::string &name() const { return _name; } + + /** The JS error, built on `runtime`. */ + jsi::Value toValue(jsi::Runtime &runtime) const { + auto message = jsi::String::createFromUtf8(runtime, what()); + auto extra = _extra ? _extra(runtime) : jsi::Value::undefined(); + auto global = runtime.global(); + // The built-in errors (TypeError, RangeError) are built as such. + if (_name == "TypeError" || _name == "RangeError") { + auto ctor = global.getProperty(runtime, _name.c_str()); + if (ctor.isObject() && ctor.asObject(runtime).isFunction(runtime)) { + return ctor.asObject(runtime).asFunction(runtime).callAsConstructor( + runtime, message); + } + } + auto registry = global.getProperty(runtime, "__RNSkiaErrors"); + if (registry.isObject()) { + auto errors = registry.asObject(runtime); + // The errors of the generic class take their name as an argument. + bool generic = !errors.hasProperty(runtime, _name.c_str()); + auto factory = + errors.getProperty(runtime, generic ? "SkiaError" : _name.c_str()); + if (factory.isObject() && factory.asObject(runtime).isFunction(runtime)) { + auto fn = factory.asObject(runtime).asFunction(runtime); + if (generic) { + return fn.call(runtime, message, + jsi::String::createFromUtf8(runtime, _name)); + } + return fn.call(runtime, message, extra); + } + } + // No registry: an Error that keeps the name and the extra field. + auto error = global.getPropertyAsFunction(runtime, "Error") + .callAsConstructor(runtime, message) + .asObject(runtime); + error.setProperty(runtime, "name", + jsi::String::createFromUtf8(runtime, _name)); + if (!_extraKey.empty()) { + error.setProperty(runtime, _extraKey.c_str(), extra); + } + return jsi::Value(runtime, error); + } + + /** The JS error, as a JSError to throw on `runtime`. */ + jsi::JSError toJSError(jsi::Runtime &runtime) const { + return jsi::JSError(runtime, toValue(runtime)); + } + +private: + std::string _name; + std::string _extraKey; + Extra _extra; +}; + +/** + Runs `body`, the work of a host function, and turns a NamedError it throws + into the JS error of that name. Other exceptions pass through as they are: + the runtime turns a std::exception into an Error with its message. + */ +template +auto guardNamedErrors(jsi::Runtime &runtime, Body &&body) -> decltype(body()) { + try { + return body(); + } catch (const NamedError &error) { + throw error.toJSError(runtime); + } +} + +} // namespace RNJsi diff --git a/packages/skia/cpp/jsi/NativeObject.h b/packages/skia/cpp/jsi/NativeObject.h index 7415adb9f5..5869a07c85 100644 --- a/packages/skia/cpp/jsi/NativeObject.h +++ b/packages/skia/cpp/jsi/NativeObject.h @@ -16,6 +16,7 @@ #include "jsi/BoxedNativeObject.h" #include "jsi/JSICache.h" +#include "jsi/NamedError.h" // Forward declare to avoid circular dependency namespace RNJsi { @@ -368,9 +369,11 @@ class NativeObject : public NativeObjectBase, runtime, jsi::PropNameID::forUtf8(runtime, name), sizeof...(Args), [method](jsi::Runtime &rt, const jsi::Value &thisVal, const jsi::Value *args, size_t count) -> jsi::Value { - auto native = NativeObject::fromValue(rt, thisVal); - return callMethod(native.get(), method, rt, args, - std::index_sequence_for{}, count); + return RNJsi::guardNamedErrors(rt, [&]() -> jsi::Value { + auto native = NativeObject::fromValue(rt, thisVal); + return callMethod(native.get(), method, rt, args, + std::index_sequence_for{}, count); + }); }); prototype.setProperty(runtime, name, func); } @@ -388,10 +391,12 @@ class NativeObject : public NativeObjectBase, runtime, jsi::PropNameID::forUtf8(runtime, name), sizeof...(Args), [method](jsi::Runtime &rt, const jsi::Value &thisVal, const jsi::Value *args, size_t count) -> jsi::Value { - auto native = NativeObject::fromValue(rt, thisVal); - return callMethodWithRuntime(native.get(), method, rt, args, - std::index_sequence_for{}, - count); + return RNJsi::guardNamedErrors(rt, [&]() -> jsi::Value { + auto native = NativeObject::fromValue(rt, thisVal); + return callMethodWithRuntime(native.get(), method, rt, args, + std::index_sequence_for{}, + count); + }); }); prototype.setProperty(runtime, name, func); } @@ -427,15 +432,17 @@ class NativeObject : public NativeObjectBase, 0, [getter](jsi::Runtime &rt, const jsi::Value &thisVal, const jsi::Value *args, size_t count) -> jsi::Value { - auto native = NativeObject::fromValue(rt, thisVal); - if constexpr (std::is_same_v) { - (native.get()->*getter)(); - return jsi::Value::undefined(); - } else { - ReturnType result = (native.get()->*getter)(); - return RNJsi::JSIConverter>::toJSI( - rt, std::move(result)); - } + return RNJsi::guardNamedErrors(rt, [&]() -> jsi::Value { + auto native = NativeObject::fromValue(rt, thisVal); + if constexpr (std::is_same_v) { + (native.get()->*getter)(); + return jsi::Value::undefined(); + } else { + ReturnType result = (native.get()->*getter)(); + return RNJsi::JSIConverter>::toJSI( + rt, std::move(result)); + } + }); }); defineGetter(runtime, prototype, name, std::move(getterFunc)); } @@ -454,8 +461,10 @@ class NativeObject : public NativeObjectBase, 0, [getter](jsi::Runtime &rt, const jsi::Value &thisVal, const jsi::Value *args, size_t count) -> jsi::Value { - auto native = NativeObject::fromValue(rt, thisVal); - return (native.get()->*getter)(rt); + return RNJsi::guardNamedErrors(rt, [&]() -> jsi::Value { + auto native = NativeObject::fromValue(rt, thisVal); + return (native.get()->*getter)(rt); + }); }); defineGetter(runtime, prototype, name, std::move(getterFunc)); } @@ -472,14 +481,16 @@ class NativeObject : public NativeObjectBase, 1, [setter](jsi::Runtime &rt, const jsi::Value &thisVal, const jsi::Value *args, size_t count) -> jsi::Value { - if (count < 1) { - throw jsi::JSError(rt, "Setter requires a value argument"); - } - auto native = NativeObject::fromValue(rt, thisVal); - auto value = RNJsi::JSIConverter>::fromJSI( - rt, args[0], false); - (native.get()->*setter)(std::move(value)); - return jsi::Value::undefined(); + return RNJsi::guardNamedErrors(rt, [&]() -> jsi::Value { + if (count < 1) { + throw jsi::JSError(rt, "Setter requires a value argument"); + } + auto native = NativeObject::fromValue(rt, thisVal); + auto value = RNJsi::JSIConverter>::fromJSI( + rt, args[0], false); + (native.get()->*setter)(std::move(value)); + return jsi::Value::undefined(); + }); }); // Use Object.defineProperty to create a proper setter @@ -522,10 +533,12 @@ class NativeObject : public NativeObjectBase, 0, [getter](jsi::Runtime &rt, const jsi::Value &thisVal, const jsi::Value *args, size_t count) -> jsi::Value { - auto native = NativeObject::fromValue(rt, thisVal); - ReturnType result = (native.get()->*getter)(); - return RNJsi::JSIConverter>::toJSI( - rt, std::move(result)); + return RNJsi::guardNamedErrors(rt, [&]() -> jsi::Value { + auto native = NativeObject::fromValue(rt, thisVal); + ReturnType result = (native.get()->*getter)(); + return RNJsi::JSIConverter>::toJSI( + rt, std::move(result)); + }); }); auto setterFunc = jsi::Function::createFromHostFunction( @@ -533,14 +546,16 @@ class NativeObject : public NativeObjectBase, 1, [setter](jsi::Runtime &rt, const jsi::Value &thisVal, const jsi::Value *args, size_t count) -> jsi::Value { - if (count < 1) { - throw jsi::JSError(rt, "Setter requires a value argument"); - } - auto native = NativeObject::fromValue(rt, thisVal); - auto value = RNJsi::JSIConverter>::fromJSI( - rt, args[0], false); - (native.get()->*setter)(std::move(value)); - return jsi::Value::undefined(); + return RNJsi::guardNamedErrors(rt, [&]() -> jsi::Value { + if (count < 1) { + throw jsi::JSError(rt, "Setter requires a value argument"); + } + auto native = NativeObject::fromValue(rt, thisVal); + auto value = RNJsi::JSIConverter>::fromJSI( + rt, args[0], false); + (native.get()->*setter)(std::move(value)); + return jsi::Value::undefined(); + }); }); auto objectCtor = runtime.global().getPropertyAsObject(runtime, "Object"); diff --git a/packages/skia/cpp/rnskia/RNSkAsync.h b/packages/skia/cpp/rnskia/RNSkAsync.h index 4b26572e34..9d2cb83174 100644 --- a/packages/skia/cpp/rnskia/RNSkAsync.h +++ b/packages/skia/cpp/rnskia/RNSkAsync.h @@ -67,6 +67,10 @@ class RNSkAsync { [promise, settle = std::move(settle)](jsi::Runtime &runtime) { try { settle(runtime, *promise); + } catch (const RNJsi::NamedError &error) { + // A SkiaDecodeError, an AbortError...: the error of + // its name. + promise->reject(error); } catch (const jsi::JSError &error) { // The JS error itself (a RangeError for a typed array // too large, say), name and stack kept. diff --git a/packages/skia/src/skia/NativeSetup.ts b/packages/skia/src/skia/NativeSetup.ts index 61968ec3ab..71e45c9a50 100644 --- a/packages/skia/src/skia/NativeSetup.ts +++ b/packages/skia/src/skia/NativeSetup.ts @@ -2,8 +2,10 @@ import { Platform } from "../Platform"; import NativeSkiaModule from "../specs/NativeSkiaModule"; import { registerSkiaWorkletSerialization } from "./SkiaWorkletSerialization"; +import { SkiaErrorConstructors } from "./types/Errors"; declare global { + var __RNSkiaErrors: typeof SkiaErrorConstructors | undefined; var __skiaScheduleOnUI: ((settle: () => void) => void) | undefined; } @@ -33,6 +35,10 @@ const registerUIRuntimeScheduler = () => { }; if (Platform.OS !== "web" && global.SkiaApi == null) { + // Native code builds the errors it throws with these, on this runtime, so + // that `instanceof SkiaDecodeError` holds (see cpp/jsi/NamedError.h). + // Registered first: installing the module can already throw one. + globalThis.__RNSkiaErrors = SkiaErrorConstructors; // Initialize RN Skia const SkiaModule = NativeSkiaModule; if (SkiaModule == null || typeof SkiaModule.install !== "function") { diff --git a/packages/skia/src/skia/__tests__/Errors.spec.ts b/packages/skia/src/skia/__tests__/Errors.spec.ts new file mode 100644 index 0000000000..7a1712c2bc --- /dev/null +++ b/packages/skia/src/skia/__tests__/Errors.spec.ts @@ -0,0 +1,74 @@ +import { + SkiaError, + SkiaDecodeError, + SkSLCompilationError, + SkiaValidationError, + SkiaOutOfMemoryError, + SkiaGPUUnavailableError, + SkiaInternalError, + SkiaErrorConstructors, + isSkiaError, +} from "../types/Errors"; + +describe("Errors", () => { + it("names each error and keeps the class chain", () => { + const errors = [ + [new SkiaDecodeError("bad bytes", "image"), "SkiaDecodeError"], + [new SkSLCompilationError("bad sksl", []), "SkSLCompilationError"], + [new SkiaValidationError("zero size"), "SkiaValidationError"], + [new SkiaOutOfMemoryError("oom"), "SkiaOutOfMemoryError"], + [new SkiaGPUUnavailableError("no vulkan"), "SkiaGPUUnavailableError"], + [new SkiaInternalError("driver"), "SkiaInternalError"], + ] as const; + for (const [error, name] of errors) { + expect(error.name).toBe(name); + expect(error).toBeInstanceOf(SkiaError); + expect(error).toBeInstanceOf(Error); + expect(isSkiaError(error)).toBe(true); + expect(isSkiaError(error, name)).toBe(true); + expect(String(error)).toBe(`${name}: ${error.message}`); + } + }); + + it("carries the extra fields", () => { + const decode = new SkiaDecodeError("bad svg", "svg"); + expect(decode.format).toBe("svg"); + const compile = new SkSLCompilationError("bad sksl", [ + { + type: "error", + message: "undeclared identifier", + lineNum: 3, + linePos: 0, + }, + ]); + expect(compile.messages).toHaveLength(1); + expect(compile.messages[0].lineNum).toBe(3); + }); + + it("names the errors of the generic class like WebGPU's DOMExceptions", () => { + const error = SkiaErrorConstructors.SkiaError("lost", "AbortError"); + expect(error).toBeInstanceOf(SkiaError); + expect(error.name).toBe("AbortError"); + expect(isSkiaError(error, "AbortError")).toBe(true); + expect(SkiaErrorConstructors.SkiaError("plain").name).toBe("SkiaError"); + }); + + it("recognizes an error by its name alone, as a worklet receives it", () => { + const plain = new Error("bad bytes"); + plain.name = "SkiaDecodeError"; + expect(isSkiaError(plain)).toBe(true); + expect(isSkiaError(plain, "SkiaDecodeError")).toBe(true); + expect(isSkiaError(plain, "AbortError")).toBe(false); + expect(isSkiaError(new TypeError("x"))).toBe(false); + expect(isSkiaError(null)).toBe(false); + expect(isSkiaError("SkiaDecodeError")).toBe(false); + }); + + it("builds the errors native code asks for", () => { + const decode = SkiaErrorConstructors.SkiaDecodeError("bad", "typeface"); + expect(decode).toBeInstanceOf(SkiaDecodeError); + expect(decode.format).toBe("typeface"); + const compile = SkiaErrorConstructors.SkSLCompilationError("bad", []); + expect(compile).toBeInstanceOf(SkSLCompilationError); + }); +}); diff --git a/packages/skia/src/skia/types/Errors.ts b/packages/skia/src/skia/types/Errors.ts new file mode 100644 index 0000000000..978a64ba65 --- /dev/null +++ b/packages/skia/src/skia/types/Errors.ts @@ -0,0 +1,170 @@ +/** + * The errors React Native Skia throws and rejects with. + * + * A factory never returns null to say it failed: it throws one of these, and + * a promise rejects with one. `null` is kept for "no result" (a path + * operation with an empty outcome, the end of an iteration), never for a + * failure. + * + * `error.name` identifies an error on every runtime. `instanceof` holds on + * the runtime that loaded the package (the React Native runtime, or the page + * on the web); a worklet runtime gets plain errors that keep their `name`, + * so code that may run in a worklet checks `name`, or uses + * {@link isSkiaError}. + */ + +/** The names of the errors below. */ +export type SkiaErrorName = + | "SkiaError" + | "SkiaDecodeError" + | "SkSLCompilationError" + | "SkiaValidationError" + | "SkiaOutOfMemoryError" + | "SkiaGPUUnavailableError" + | "SkiaInternalError" + // Named like the DOMException WebGPU uses for the same situation. + | "NotSupportedError" + | "AbortError" + | "NotFoundError"; + +/** The base class of the errors React Native Skia raises. */ +export class SkiaError extends Error { + constructor(message?: string, name: SkiaErrorName = "SkiaError") { + super(message); + this.name = name; + // Transpiled classes extending Error lose their prototype. + Object.setPrototypeOf(this, new.target.prototype); + } +} + +/** What a {@link SkiaDecodeError} was decoding. */ +export type SkiaDecodeFormat = + | "image" + | "animated-image" + | "svg" + | "typeface" + | "skottie" + | "picture" + | "path"; + +/** + * Bytes or text that cannot be decoded or parsed: an image, an SVG, a font, + * a Lottie file, a serialized picture, an SVG path string. + */ +export class SkiaDecodeError extends SkiaError { + readonly format: SkiaDecodeFormat; + constructor(message: string, format: SkiaDecodeFormat) { + super(message, "SkiaDecodeError"); + this.format = format; + } +} + +/** One diagnostic of an SkSL compilation, like WebGPU's GPUCompilationMessage. */ +export interface SkSLCompilationMessage { + readonly type: "error" | "warning" | "info"; + readonly message: string; + /** 1-based line of the source, 0 when unknown. */ + readonly lineNum: number; + /** 1-based position in the line, 0 when unknown. */ + readonly linePos: number; +} + +/** SkSL that fails to compile, with its diagnostics. */ +export class SkSLCompilationError extends SkiaError { + readonly messages: readonly SkSLCompilationMessage[]; + constructor(message: string, messages: readonly SkSLCompilationMessage[]) { + super(message, "SkSLCompilationError"); + this.messages = messages; + } +} + +/** + * Invalid use the types cannot catch: a surface of size zero, pixel data + * shorter than its image info, a texture without the usage it needs. + */ +export class SkiaValidationError extends SkiaError { + constructor(message: string) { + super(message, "SkiaValidationError"); + } +} + +/** An allocation failed, on the GPU or the CPU. */ +export class SkiaOutOfMemoryError extends SkiaError { + constructor(message: string) { + super(message, "SkiaOutOfMemoryError"); + } +} + +/** + * The device has no GPU Skia can render with (see `Skia.gpu`): the message + * is `Skia.gpu.error`. + */ +export class SkiaGPUUnavailableError extends SkiaError { + constructor(message: string) { + super(message, "SkiaGPUUnavailableError"); + } +} + +/** Skia or the graphics driver failed on its own. */ +export class SkiaInternalError extends SkiaError { + constructor(message: string) { + super(message, "SkiaInternalError"); + } +} + +/** + * Whether `error` is one React Native Skia raised, optionally of the given + * name. Works on every runtime, worklets included, as it reads the name. + */ +export const isSkiaError = ( + error: unknown, + name?: SkiaErrorName +): error is SkiaError => { + "worklet"; + if ( + typeof error !== "object" || + error === null || + typeof (error as { name?: unknown }).name !== "string" + ) { + return false; + } + const errorName = (error as { name: string }).name; + if (name !== undefined) { + return errorName === name; + } + return SkiaErrorNames.indexOf(errorName as SkiaErrorName) !== -1; +}; + +const SkiaErrorNames: readonly SkiaErrorName[] = [ + "SkiaError", + "SkiaDecodeError", + "SkSLCompilationError", + "SkiaValidationError", + "SkiaOutOfMemoryError", + "SkiaGPUUnavailableError", + "SkiaInternalError", + "NotSupportedError", + "AbortError", + "NotFoundError", +]; + +/** + * The constructors native code builds its errors with, on the runtime that + * loaded the package: `instanceof` then holds there. Each takes the message + * and, for the errors that carry more, the extra field. + */ +export const SkiaErrorConstructors = { + SkiaError: (message: string, name?: SkiaErrorName) => + new SkiaError(message, name), + SkiaDecodeError: (message: string, format: SkiaDecodeFormat) => + new SkiaDecodeError(message, format), + SkSLCompilationError: ( + message: string, + messages: readonly SkSLCompilationMessage[] + ) => new SkSLCompilationError(message, messages), + SkiaValidationError: (message: string) => new SkiaValidationError(message), + SkiaOutOfMemoryError: (message: string) => new SkiaOutOfMemoryError(message), + SkiaGPUUnavailableError: (message: string) => + new SkiaGPUUnavailableError(message), + SkiaInternalError: (message: string) => new SkiaInternalError(message), +}; diff --git a/packages/skia/src/skia/types/index.ts b/packages/skia/src/skia/types/index.ts index 8339fb08e5..59a900a959 100644 --- a/packages/skia/src/skia/types/index.ts +++ b/packages/skia/src/skia/types/index.ts @@ -34,3 +34,4 @@ export * from "./Recorder"; export * from "./Skottie"; export * from "./Graphite"; export * from "./GPUTexture"; +export * from "./Errors"; diff --git a/packages/skia/src/skia/web/Host.ts b/packages/skia/src/skia/web/Host.ts index 26dd18247f..d6839905f0 100644 --- a/packages/skia/src/skia/web/Host.ts +++ b/packages/skia/src/skia/web/Host.ts @@ -1,12 +1,16 @@ import type { CanvasKit, EmbindEnumEntity } from "canvaskit-wasm"; import type { SkJSIInstance } from "../types"; +import { SkiaError } from "../types/Errors"; export const throwNotImplementedOnRNWeb = (): T => { if (typeof jest !== "undefined") { return jest.fn() as unknown as T; } - throw new Error("Not implemented on React Native Web"); + throw new SkiaError( + "Not implemented on React Native Web", + "NotSupportedError" + ); }; export abstract class Host { From cfd50a47d2ee98203c6fc57d5099135c56ad5e28 Mon Sep 17 00:00:00 2001 From: William Candillon Date: Thu, 26 Nov 2026 13:42:56 +0000 Subject: [PATCH 2/3] =?UTF-8?q?fix(=F0=9F=9A=A8):=20recognize=20Skia=20err?= =?UTF-8?q?ors=20by=20a=20brand,=20not=20by=20their=20name?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit isSkiaError matched on the error name alone, so a DOMException of the same name (the AbortError of an aborted fetch) passed as a Skia error. The errors now carry a non-enumerable __rnskiaError brand, set by the SkiaError class and by NamedError when it builds a plain Error on a runtime without the classes, and isSkiaError requires it. This also removes the worklet's capture of SkiaErrorNames, which was declared after isSkiaError and read before its initialization. --- apps/docs/docs/errors.md | 2 +- packages/skia/cpp/jsi/NamedError.h | 12 ++++++- .../skia/src/skia/__tests__/Errors.spec.ts | 23 ++++++++++++- packages/skia/src/skia/types/Errors.ts | 34 ++++++++----------- 4 files changed, 48 insertions(+), 23 deletions(-) diff --git a/apps/docs/docs/errors.md b/apps/docs/docs/errors.md index a209311efb..3783242bb7 100644 --- a/apps/docs/docs/errors.md +++ b/apps/docs/docs/errors.md @@ -50,7 +50,7 @@ try { } ``` -`instanceof` holds on the React Native runtime (and on the web). A worklet runtime receives errors that keep their `name`, message and extra field, but not their class. In code that may run in a worklet, check the name, or use `isSkiaError`: +`instanceof` holds on the React Native runtime (and on the web). A worklet runtime receives errors that keep their `name`, message and extra field, but not their class. In code that may run in a worklet, use `isSkiaError`: it recognizes the errors React Native Skia raised by a marker they carry, so an error of the same name from elsewhere (the `AbortError` of an aborted `fetch`) does not match. ```tsx import { isSkiaError } from "react-native-skia"; diff --git a/packages/skia/cpp/jsi/NamedError.h b/packages/skia/cpp/jsi/NamedError.h index 7f0bf56e55..d467f6dbde 100644 --- a/packages/skia/cpp/jsi/NamedError.h +++ b/packages/skia/cpp/jsi/NamedError.h @@ -71,7 +71,9 @@ class NamedError : public std::runtime_error { return fn.call(runtime, message, extra); } } - // No registry: an Error that keeps the name and the extra field. + // No registry: an Error that keeps the name and the extra field, and + // carries the brand the classes set (SkiaErrorBrand in Errors.ts), so + // that isSkiaError recognizes it. auto error = global.getPropertyAsFunction(runtime, "Error") .callAsConstructor(runtime, message) .asObject(runtime); @@ -80,6 +82,11 @@ class NamedError : public std::runtime_error { if (!_extraKey.empty()) { error.setProperty(runtime, _extraKey.c_str(), extra); } + auto descriptor = jsi::Object(runtime); + descriptor.setProperty(runtime, "value", true); + global.getPropertyAsObject(runtime, "Object") + .getPropertyAsFunction(runtime, "defineProperty") + .call(runtime, error, kBrand, descriptor); return jsi::Value(runtime, error); } @@ -89,6 +96,9 @@ class NamedError : public std::runtime_error { } private: + /** SkiaErrorBrand in src/skia/types/Errors.ts. */ + static constexpr const char *kBrand = "__rnskiaError"; + std::string _name; std::string _extraKey; Extra _extra; diff --git a/packages/skia/src/skia/__tests__/Errors.spec.ts b/packages/skia/src/skia/__tests__/Errors.spec.ts index 7a1712c2bc..5bc9adc366 100644 --- a/packages/skia/src/skia/__tests__/Errors.spec.ts +++ b/packages/skia/src/skia/__tests__/Errors.spec.ts @@ -7,6 +7,7 @@ import { SkiaGPUUnavailableError, SkiaInternalError, SkiaErrorConstructors, + SkiaErrorBrand, isSkiaError, } from "../types/Errors"; @@ -53,9 +54,10 @@ describe("Errors", () => { expect(SkiaErrorConstructors.SkiaError("plain").name).toBe("SkiaError"); }); - it("recognizes an error by its name alone, as a worklet receives it", () => { + it("recognizes a branded error, as a worklet receives it", () => { const plain = new Error("bad bytes"); plain.name = "SkiaDecodeError"; + Object.defineProperty(plain, SkiaErrorBrand, { value: true }); expect(isSkiaError(plain)).toBe(true); expect(isSkiaError(plain, "SkiaDecodeError")).toBe(true); expect(isSkiaError(plain, "AbortError")).toBe(false); @@ -64,6 +66,25 @@ describe("Errors", () => { expect(isSkiaError("SkiaDecodeError")).toBe(false); }); + it("does not take an error of the same name for its own", () => { + // The AbortError of an aborted fetch, a DOMException. + const abort = new Error("aborted"); + abort.name = "AbortError"; + expect(isSkiaError(abort)).toBe(false); + expect(isSkiaError(abort, "AbortError")).toBe(false); + const decode = new Error("bad bytes"); + decode.name = "SkiaDecodeError"; + expect(isSkiaError(decode)).toBe(false); + }); + + it("brands the errors without showing the brand", () => { + const error = new SkiaDecodeError("bad", "image"); + expect(Object.keys(error)).not.toContain(SkiaErrorBrand); + expect((error as unknown as Record)[SkiaErrorBrand]).toBe( + true + ); + }); + it("builds the errors native code asks for", () => { const decode = SkiaErrorConstructors.SkiaDecodeError("bad", "typeface"); expect(decode).toBeInstanceOf(SkiaDecodeError); diff --git a/packages/skia/src/skia/types/Errors.ts b/packages/skia/src/skia/types/Errors.ts index 978a64ba65..b128154ac6 100644 --- a/packages/skia/src/skia/types/Errors.ts +++ b/packages/skia/src/skia/types/Errors.ts @@ -27,11 +27,21 @@ export type SkiaErrorName = | "AbortError" | "NotFoundError"; +/** + * The non-enumerable property, set to `true`, that marks an error React + * Native Skia raised, on every runtime: the classes below set it, and so does + * native code when it builds an error on a runtime without them (a worklet + * runtime, see cpp/jsi/NamedError.h). Unlike the name, it does not match a + * DOMException of the same name (the `AbortError` of an aborted fetch). + */ +export const SkiaErrorBrand = "__rnskiaError"; + /** The base class of the errors React Native Skia raises. */ export class SkiaError extends Error { constructor(message?: string, name: SkiaErrorName = "SkiaError") { super(message); this.name = name; + Object.defineProperty(this, SkiaErrorBrand, { value: true }); // Transpiled classes extending Error lose their prototype. Object.setPrototypeOf(this, new.target.prototype); } @@ -114,7 +124,8 @@ export class SkiaInternalError extends SkiaError { /** * Whether `error` is one React Native Skia raised, optionally of the given - * name. Works on every runtime, worklets included, as it reads the name. + * name. Works on every runtime, worklets included, as it reads the + * {@link SkiaErrorBrand} rather than the class. */ export const isSkiaError = ( error: unknown, @@ -124,30 +135,13 @@ export const isSkiaError = ( if ( typeof error !== "object" || error === null || - typeof (error as { name?: unknown }).name !== "string" + (error as Record)[SkiaErrorBrand] !== true ) { return false; } - const errorName = (error as { name: string }).name; - if (name !== undefined) { - return errorName === name; - } - return SkiaErrorNames.indexOf(errorName as SkiaErrorName) !== -1; + return name === undefined || (error as { name?: unknown }).name === name; }; -const SkiaErrorNames: readonly SkiaErrorName[] = [ - "SkiaError", - "SkiaDecodeError", - "SkSLCompilationError", - "SkiaValidationError", - "SkiaOutOfMemoryError", - "SkiaGPUUnavailableError", - "SkiaInternalError", - "NotSupportedError", - "AbortError", - "NotFoundError", -]; - /** * The constructors native code builds its errors with, on the runtime that * loaded the package: `instanceof` then holds there. Each takes the message From fdb50a4043d16f6da74683523444ae0fa2d06422 Mon Sep 17 00:00:00 2001 From: William Candillon Date: Thu, 26 Nov 2026 13:53:24 +0000 Subject: [PATCH 3/3] =?UTF-8?q?feat(=F0=9F=9A=A8):=20throw=20SkiaSurfaceUn?= =?UTF-8?q?availableError=20when=20the=20web=20has=20no=20drawing=20surfac?= =?UTF-8?q?e?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit The web renderer and the shared WebGL context threw plain Errors when the browser refused a WebGL, graphics or 2D context, so apps had to match the message to show an empty state. They now throw SkiaSurfaceUnavailableError, whose context field says which one failed (webgl, graphics or 2d). --- apps/docs/docs/errors.md | 13 +++++ .../skia/src/skia/__tests__/Errors.spec.ts | 7 +++ packages/skia/src/skia/types/Errors.ts | 22 ++++++++ .../skia/src/skia/web/SharedWebGLContext.ts | 17 ++++-- .../web/__tests__/SharedWebGLContext.spec.ts | 42 +++++++++++++++ packages/skia/src/views/SkiaWebRenderer.ts | 11 +++- .../__tests__/SkiaWebRenderer.web.spec.ts | 52 +++++++++++++++++++ 7 files changed, 159 insertions(+), 5 deletions(-) create mode 100644 packages/skia/src/views/__tests__/SkiaWebRenderer.web.spec.ts diff --git a/apps/docs/docs/errors.md b/apps/docs/docs/errors.md index 3783242bb7..9cbce467df 100644 --- a/apps/docs/docs/errors.md +++ b/apps/docs/docs/errors.md @@ -15,6 +15,7 @@ React Native Skia reports failures the way WebGPU does: a call that fails throws | Data that cannot be decoded, parsed or compiled | Throws a `SkiaDecodeError` or an `SkSLCompilationError` | | A GPU or CPU allocation that fails | Throws a `SkiaOutOfMemoryError` or a `SkiaValidationError` | | No GPU on the device | Throws a `SkiaGPUUnavailableError` (see [`Skia.gpu`](/docs/webgpu#the-gpu-device)) | +| No drawing surface in the browser | Throws a `SkiaSurfaceUnavailableError` | | A valid call without a result (a path operation with an empty outcome, the end of an iteration) | Returns `null` | | Asynchronous work that fails | Rejects with a named error | | An API the platform does not have | Throws an error named `NotSupportedError` | @@ -30,6 +31,7 @@ Every error React Native Skia raises extends `SkiaError`, which extends `Error`. | `SkiaValidationError` | A call is invalid in a way the types cannot catch: a surface of size zero, pixel data shorter than its image info. | | | `SkiaOutOfMemoryError` | An allocation fails. | | | `SkiaGPUUnavailableError` | The device has no GPU Skia can render with. The message is `Skia.gpu.error`. | | +| `SkiaSurfaceUnavailableError` | On the web, the browser will not give a drawing surface: no WebGL context (WebGL disabled or blocked, too many contexts on the page), no graphics context on top of it, or no 2D context to present through. | `context`: `"webgl"`, `"graphics"` or `"2d"`. | | `SkiaInternalError` | Skia or the graphics driver fails on its own. | | Three more names follow the `DOMException` names WebGPU uses, as plain `SkiaError`s: `NotSupportedError`, `AbortError` and `NotFoundError`. @@ -62,3 +64,14 @@ const onError = (e: unknown) => { } }; ``` + +### An unavailable drawing surface on the web + +A browser can refuse a view its drawing surface: WebGL turned off or blocked, or too many WebGL contexts on the page. Catch it with an error boundary and show an empty state. Check the class, not the message, which may change: + +```tsx +import { SkiaSurfaceUnavailableError } from "react-native-skia"; + +const isSurfaceUnavailable = (error: unknown) => + error instanceof SkiaSurfaceUnavailableError; +``` diff --git a/packages/skia/src/skia/__tests__/Errors.spec.ts b/packages/skia/src/skia/__tests__/Errors.spec.ts index 5bc9adc366..c7f3c24410 100644 --- a/packages/skia/src/skia/__tests__/Errors.spec.ts +++ b/packages/skia/src/skia/__tests__/Errors.spec.ts @@ -5,6 +5,7 @@ import { SkiaValidationError, SkiaOutOfMemoryError, SkiaGPUUnavailableError, + SkiaSurfaceUnavailableError, SkiaInternalError, SkiaErrorConstructors, SkiaErrorBrand, @@ -19,6 +20,10 @@ describe("Errors", () => { [new SkiaValidationError("zero size"), "SkiaValidationError"], [new SkiaOutOfMemoryError("oom"), "SkiaOutOfMemoryError"], [new SkiaGPUUnavailableError("no vulkan"), "SkiaGPUUnavailableError"], + [ + new SkiaSurfaceUnavailableError("no webgl", "webgl"), + "SkiaSurfaceUnavailableError", + ], [new SkiaInternalError("driver"), "SkiaInternalError"], ] as const; for (const [error, name] of errors) { @@ -44,6 +49,8 @@ describe("Errors", () => { ]); expect(compile.messages).toHaveLength(1); expect(compile.messages[0].lineNum).toBe(3); + const surface = new SkiaSurfaceUnavailableError("no 2d", "2d"); + expect(surface.context).toBe("2d"); }); it("names the errors of the generic class like WebGPU's DOMExceptions", () => { diff --git a/packages/skia/src/skia/types/Errors.ts b/packages/skia/src/skia/types/Errors.ts index b128154ac6..5c564df7f4 100644 --- a/packages/skia/src/skia/types/Errors.ts +++ b/packages/skia/src/skia/types/Errors.ts @@ -21,6 +21,7 @@ export type SkiaErrorName = | "SkiaValidationError" | "SkiaOutOfMemoryError" | "SkiaGPUUnavailableError" + | "SkiaSurfaceUnavailableError" | "SkiaInternalError" // Named like the DOMException WebGPU uses for the same situation. | "NotSupportedError" @@ -115,6 +116,25 @@ export class SkiaGPUUnavailableError extends SkiaError { } } +/** What a {@link SkiaSurfaceUnavailableError} could not get. */ +export type SkiaSurfaceContext = "webgl" | "graphics" | "2d"; + +/** + * The browser would not give a drawing surface to render or present with: + * no WebGL context (WebGL disabled or blocked, too many contexts on the + * page), no graphics context on top of it, or no 2D context to present the + * frame through. On the web only, where a view can fall back to an empty + * state. Identify it by its class or name, never by its message, which may + * change. + */ +export class SkiaSurfaceUnavailableError extends SkiaError { + readonly context: SkiaSurfaceContext; + constructor(message: string, context: SkiaSurfaceContext) { + super(message, "SkiaSurfaceUnavailableError"); + this.context = context; + } +} + /** Skia or the graphics driver failed on its own. */ export class SkiaInternalError extends SkiaError { constructor(message: string) { @@ -160,5 +180,7 @@ export const SkiaErrorConstructors = { SkiaOutOfMemoryError: (message: string) => new SkiaOutOfMemoryError(message), SkiaGPUUnavailableError: (message: string) => new SkiaGPUUnavailableError(message), + SkiaSurfaceUnavailableError: (message: string, context: SkiaSurfaceContext) => + new SkiaSurfaceUnavailableError(message, context), SkiaInternalError: (message: string) => new SkiaInternalError(message), }; diff --git a/packages/skia/src/skia/web/SharedWebGLContext.ts b/packages/skia/src/skia/web/SharedWebGLContext.ts index bdfea2e0d6..c4e172e79a 100644 --- a/packages/skia/src/skia/web/SharedWebGLContext.ts +++ b/packages/skia/src/skia/web/SharedWebGLContext.ts @@ -5,6 +5,8 @@ import type { WebGLContextHandle, } from "canvaskit-wasm"; +import { SkiaSurfaceUnavailableError } from "../types/Errors"; + import { JsiSkSurface } from "./JsiSkSurface"; // One WebGL context per CanvasKit instance, shared by every on the @@ -107,7 +109,10 @@ export class SharedWebGLContext { const gl = getGL(canvas); if (!gl) { deleteContextHandle(CanvasKit, handle); - throw new Error("Could not create a WebGL context"); + throw new SkiaSurfaceUnavailableError( + "Could not create a WebGL context", + "webgl" + ); } this.gl = gl; this.build(handle); @@ -131,7 +136,10 @@ export class SharedWebGLContext { private createHandle() { const handle = this.CanvasKit.GetWebGLContext(this.canvas); if (!handle) { - throw new Error("Could not create a WebGL context"); + throw new SkiaSurfaceUnavailableError( + "Could not create a WebGL context", + "webgl" + ); } return handle; } @@ -148,7 +156,10 @@ export class SharedWebGLContext { } } if (!grContext) { - throw new Error("Could not create a graphics context"); + throw new SkiaSurfaceUnavailableError( + "Could not create a graphics context", + "graphics" + ); } this.handle = handle; this.grContext = grContext; diff --git a/packages/skia/src/skia/web/__tests__/SharedWebGLContext.spec.ts b/packages/skia/src/skia/web/__tests__/SharedWebGLContext.spec.ts index d567a34e22..de70d85eef 100644 --- a/packages/skia/src/skia/web/__tests__/SharedWebGLContext.spec.ts +++ b/packages/skia/src/skia/web/__tests__/SharedWebGLContext.spec.ts @@ -15,6 +15,7 @@ import { } from "../../../views/__tests__/web-setup"; import { JsiSkSurfaceFactory } from "../JsiSkSurfaceFactory"; import { getSharedWebGLContext } from "../SharedWebGLContext"; +import { SkiaSurfaceUnavailableError, isSkiaError } from "../../types/Errors"; // Offscreen surfaces on the shared WebGL context: one context for all of // them (a context per surface, never released, used to run into the @@ -136,6 +137,47 @@ describe("SharedWebGLContext", () => { expect(registry.size).toBe(1); }); + // Apps fall back to an empty state on these: they are recognized by their + // class and name, whatever their message says. + const surfaceError = (run: () => unknown) => { + try { + run(); + } catch (e) { + return e; + } + throw new Error("expected the call to throw"); + }; + + it("throws a SkiaSurfaceUnavailableError without a WebGL context", () => { + const { Surface, CanvasKitMock, registry } = factory(); + CanvasKitMock.GetWebGLContext.mockImplementationOnce(() => 0); + const error = surfaceError(() => Surface.MakeOffscreen(8, 8)); + expect(error).toBeInstanceOf(SkiaSurfaceUnavailableError); + expect((error as SkiaSurfaceUnavailableError).context).toBe("webgl"); + expect(isSkiaError(error, "SkiaSurfaceUnavailableError")).toBe(true); + expect(registry.size).toBe(0); + }); + + it("throws a SkiaSurfaceUnavailableError without a graphics context", () => { + const { Surface, CanvasKitMock, registry } = factory(); + CanvasKitMock.MakeWebGLContext.mockImplementationOnce(() => null); + const error = surfaceError(() => Surface.MakeOffscreen(8, 8)); + expect(error).toBeInstanceOf(SkiaSurfaceUnavailableError); + expect((error as SkiaSurfaceUnavailableError).context).toBe("graphics"); + expect(registry.size).toBe(0); + }); + + it("does not report other failures as an unavailable surface", () => { + const { Surface, CanvasKitMock } = factory(); + CanvasKitMock.MakeWebGLContext.mockImplementationOnce(() => { + throw new Error("Could not create a WebGL context"); + }); + // The same words, from somewhere else: not one of ours. + const error = surfaceError(() => Surface.MakeOffscreen(8, 8)); + expect(error).not.toBeInstanceOf(SkiaSurfaceUnavailableError); + expect(isSkiaError(error)).toBe(false); + }); + it("reuses the surfaces of many sizes drawn in turn", () => { const { CanvasKitMock } = factory(); const shared = getSharedWebGLContext( diff --git a/packages/skia/src/views/SkiaWebRenderer.ts b/packages/skia/src/views/SkiaWebRenderer.ts index 00f87f2219..ce38718388 100644 --- a/packages/skia/src/views/SkiaWebRenderer.ts +++ b/packages/skia/src/views/SkiaWebRenderer.ts @@ -4,6 +4,7 @@ import { useLayoutEffect, useRef } from "react"; import type { LayoutChangeEvent } from "react-native"; import type { SkRect, SkPicture, SkImage } from "../skia/types"; +import { SkiaSurfaceUnavailableError } from "../skia/types/Errors"; import { getSharedWebGLContext } from "../skia/web/SharedWebGLContext"; import type { SharedWebGLContext } from "../skia/web/SharedWebGLContext"; @@ -69,7 +70,10 @@ export class WebGLRenderer implements Renderer { ) { const shared = getSharedWebGLContext(CanvasKit); if (!shared) { - throw new Error("Could not create a WebGL context"); + throw new SkiaSurfaceUnavailableError( + "Could not create a WebGL context", + "webgl" + ); } this.shared = shared; // Wide gamut, like the shared drawing buffer the frame comes from (see @@ -77,7 +81,10 @@ export class WebGLRenderer implements Renderer { // the frame to sRGB. const ctx = canvas.getContext("2d", { colorSpace: "display-p3" }); if (!ctx) { - throw new Error("Could not create a 2D context"); + throw new SkiaSurfaceUnavailableError( + "Could not create a 2D context", + "2d" + ); } this.ctx = ctx; owners.set(canvas, this); diff --git a/packages/skia/src/views/__tests__/SkiaWebRenderer.web.spec.ts b/packages/skia/src/views/__tests__/SkiaWebRenderer.web.spec.ts new file mode 100644 index 0000000000..ecd37e511c --- /dev/null +++ b/packages/skia/src/views/__tests__/SkiaWebRenderer.web.spec.ts @@ -0,0 +1,52 @@ +/** + * @jest-environment jsdom + */ +import { + SkiaSurfaceUnavailableError, + isSkiaError, +} from "../../skia/types/Errors"; +import { WebGLRenderer } from "../SkiaWebRenderer"; + +import { + installWebEnvironment, + resetWebEnvironment, + installCanvasKit, +} from "./web-setup"; + +// The errors a view raises when the browser will not give it a drawing +// surface. Apps show an empty state for them, so they are recognized by +// their class and name, whatever their message says. + +beforeAll(installWebEnvironment); + +beforeEach(resetWebEnvironment); + +const construct = (canvas: HTMLCanvasElement) => { + try { + new WebGLRenderer(canvas, () => {}); + } catch (e) { + return e; + } + throw new Error("expected the renderer to throw"); +}; + +describe("WebGLRenderer", () => { + it("throws a SkiaSurfaceUnavailableError without a 2D context", () => { + installCanvasKit(); + const canvas = document.createElement("canvas"); + // A canvas that already has a WebGL context has no 2D one to give. + canvas.getContext("webgl2"); + const error = construct(canvas); + expect(error).toBeInstanceOf(SkiaSurfaceUnavailableError); + expect((error as SkiaSurfaceUnavailableError).context).toBe("2d"); + expect(isSkiaError(error, "SkiaSurfaceUnavailableError")).toBe(true); + }); + + it("throws a SkiaSurfaceUnavailableError without a WebGL context", () => { + const { CanvasKitMock } = installCanvasKit(); + CanvasKitMock.GetWebGLContext.mockImplementationOnce(() => 0); + const error = construct(document.createElement("canvas")); + expect(error).toBeInstanceOf(SkiaSurfaceUnavailableError); + expect((error as SkiaSurfaceUnavailableError).context).toBe("webgl"); + }); +});