Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
77 changes: 77 additions & 0 deletions apps/docs/docs/errors.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,77 @@
---
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)) |
| 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` |

## 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`. | |
| `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`.

## 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, 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";

const onError = (e: unknown) => {
"worklet";
if (isSkiaError(e, "AbortError")) {
// The GPU device was lost while the work was pending.
}
};
```

### 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;
```
5 changes: 5 additions & 0 deletions apps/docs/sidebars.js
Original file line number Diff line number Diff line change
Expand Up @@ -31,6 +31,11 @@ const sidebars = {
label: "WebGPU",
id: "webgpu",
},
{
type: "doc",
label: "Errors",
id: "errors",
},
{
collapsed: true,
type: "category",
Expand Down
32 changes: 19 additions & 13 deletions packages/skia/cpp/api/JsiSkNativeObjects.h
Original file line number Diff line number Diff line change
Expand Up @@ -213,8 +213,10 @@ class JsiSkNativeObject : public RNJsi::NativeObject<Derived> {
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);
}
Expand All @@ -233,10 +235,12 @@ class JsiSkNativeObject : public RNJsi::NativeObject<Derived> {
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<Args...>{}, 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<Args...>{}, count);
return jsi::Value(rt, thisValue);
});
});
prototype.setProperty(runtime, name, func);
}
Expand All @@ -254,10 +258,13 @@ class JsiSkNativeObject : public RNJsi::NativeObject<Derived> {
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<Args...>{}, 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<Args...>{},
count);
return jsi::Value(rt, thisValue);
});
});
prototype.setProperty(runtime, name, func);
}
Expand All @@ -279,9 +286,8 @@ class JsiSkNativeObject : public RNJsi::NativeObject<Derived> {
Derived *obj, ReturnType (Derived::*method)(jsi::Runtime &, Args...),
jsi::Runtime &runtime, const jsi::Value *args, std::index_sequence<Is...>,
size_t count) {
(obj->*method)(runtime,
RNJsi::JSIConverter<std::decay_t<Args>>::fromJSI(
runtime, args[Is], Is >= count)...);
(obj->*method)(runtime, RNJsi::JSIConverter<std::decay_t<Args>>::fromJSI(
runtime, args[Is], Is >= count)...);
}

std::shared_ptr<RNSkPlatformContext> _context;
Expand Down
13 changes: 11 additions & 2 deletions packages/skia/cpp/jsi/JsiPromises.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -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) {
Expand All @@ -33,8 +37,13 @@ JsiPromises::createPromiseAsJSIValue(jsi::Runtime &rt,
jsi::Function reject = args[1].getObject(rt2).getFunction(rt2);
auto wrapper = std::make_shared<Promise>(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);
Expand Down
3 changes: 3 additions & 0 deletions packages/skia/cpp/jsi/JsiPromises.h
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@
#include <jsi/jsi.h>

#include "api/third_party/base64.h"
#include "jsi/NamedError.h"

namespace RNJsi {
namespace jsi = facebook::jsi;
Expand Down Expand Up @@ -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_;
Expand Down
121 changes: 121 additions & 0 deletions packages/skia/cpp/jsi/NamedError.h
Original file line number Diff line number Diff line change
@@ -0,0 +1,121 @@
#pragma once

#include <functional>
#include <stdexcept>
#include <string>
#include <utility>

#include <jsi/jsi.h>

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<jsi::Value(jsi::Runtime &)>;

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, 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);
error.setProperty(runtime, "name",
jsi::String::createFromUtf8(runtime, _name));
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);
}

/** The JS error, as a JSError to throw on `runtime`. */
jsi::JSError toJSError(jsi::Runtime &runtime) const {
return jsi::JSError(runtime, toValue(runtime));
}

private:
/** SkiaErrorBrand in src/skia/types/Errors.ts. */
static constexpr const char *kBrand = "__rnskiaError";

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 <typename Body>
auto guardNamedErrors(jsi::Runtime &runtime, Body &&body) -> decltype(body()) {
try {
return body();
} catch (const NamedError &error) {
throw error.toJSError(runtime);
}
}

} // namespace RNJsi
Loading
Loading