Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat: remove castError #2026

Draft
wants to merge 5 commits into
base: main
Choose a base branch
from
Draft
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
55 changes: 27 additions & 28 deletions packages/solid/src/reactive/signal.ts
Original file line number Diff line number Diff line change
Expand Up @@ -613,41 +613,46 @@ export function createResource<T, S, R>(
[value, setValue] = (options.storage || createSignal)(options.initialValue) as Signal<
T | undefined
>,
[error, setError] = createSignal<unknown>(undefined),
[error, setError] = createSignal<unknown>(undefined, { equals: false }),
[track, trigger] = createSignal(undefined, { equals: false }),
[state, setState] = createSignal<"unresolved" | "pending" | "ready" | "refreshing" | "errored">(
resolved ? "ready" : "unresolved"
);
),
[pState, setPState] = createSignal<0 | 1 | 2>(0);

if (sharedConfig.context) {
id = `${sharedConfig.context.id}${sharedConfig.context.count++}`;
let v;
if (options.ssrLoadFrom === "initial") initP = options.initialValue as T;
else if (sharedConfig.load && (v = sharedConfig.load(id))) initP = v;
}
function loadEnd(p: Promise<T> | null, v: T | undefined, error?: any, key?: S) {
function loadEnd(p: Promise<T> | null, isSuccess: boolean, v: any, key?: S) {
if (pr === p) {
pr = null;
key !== undefined && (resolved = true);
if ((p === initP || v === initP) && options.onHydrated)
if ((p === initP || (isSuccess && v === initP)) && options.onHydrated)
queueMicrotask(() => options.onHydrated!(key, { value: v }));
initP = NO_INIT;
if (Transition && p && loadedUnderTransition) {
Transition.promises.delete(p);
loadedUnderTransition = false;
runUpdates(() => {
Transition!.running = true;
completeLoad(v, error);
completeLoad(isSuccess, v);
}, false);
} else completeLoad(v, error);
} else completeLoad(isSuccess, v);
}
return v;
if (isSuccess) return v;
// TODO why aren't we rethrowing
return undefined;
}
function completeLoad(v: T | undefined, err: any) {
function completeLoad(isSuccess: boolean, v: any) {
runUpdates(() => {
if (err === undefined) setValue(() => v);
setState(err !== undefined ? "errored" : resolved ? "ready" : "unresolved");
setError(err);
setState(!isSuccess ? "errored" : resolved ? "ready" : "unresolved");
setPState(isSuccess ? 1 : 2);
if (isSuccess) {
setValue(() => v);
} else setError(() => v);
for (const c of contexts.keys()) c.decrement!();
contexts.clear();
}, false);
Expand All @@ -657,7 +662,7 @@ export function createResource<T, S, R>(
const c = SuspenseContext && useContext(SuspenseContext),
v = value(),
err = error();
if (err !== undefined && !pr) throw err;
if (pState() === 2 && !pr) throw err;
if (Listener && !Listener.user && c) {
createComputed(() => {
track();
Expand All @@ -678,7 +683,7 @@ export function createResource<T, S, R>(
const lookup = dynamic ? dynamic() : (source as S);
loadedUnderTransition = Transition && Transition.running;
if (lookup == null || lookup === false) {
loadEnd(pr, untrack(value));
loadEnd(pr, true, untrack(value));
return;
}
if (Transition && pr) Transition.promises.delete(pr);
Expand All @@ -692,24 +697,24 @@ export function createResource<T, S, R>(
})
);
if (!isPromise(p)) {
loadEnd(pr, p, undefined, lookup);
loadEnd(pr, true, p, lookup);
return p;
}
pr = p;
if ("value" in p) {
if ((p as any).status === "success") loadEnd(pr, p.value as T, undefined, lookup);
else loadEnd(pr, undefined, undefined, lookup);
loadEnd(pr, (p as any).status === "success", p.value, lookup);
return p;
}
scheduled = true;
queueMicrotask(() => (scheduled = false));
runUpdates(() => {
setPState(0);
setState(resolved ? "refreshing" : "pending");
trigger();
}, false);
return p.then(
v => loadEnd(p, v, undefined, lookup),
e => loadEnd(p, undefined, castError(e), lookup)
v => loadEnd(p, true, v, lookup),
e => loadEnd(p, false, e, lookup)
) as Promise<T>;
}
Object.defineProperties(read, {
Expand All @@ -725,7 +730,7 @@ export function createResource<T, S, R>(
get() {
if (!resolved) return read();
const err = error();
if (err && !pr) throw err;
if (pState() === 2 && !pr) throw err;
return value();
}
}
Expand Down Expand Up @@ -1683,11 +1688,6 @@ function reset(node: Computation<any>, top?: boolean) {
}
}

function castError(err: unknown): Error {
if (err instanceof Error) return err;
return new Error(typeof err === "string" ? err : "Unknown error", { cause: err });
}

function runErrors(err: unknown, fns: ((err: any) => void)[], owner: Owner | null) {
try {
for (const f of fns) f(err);
Expand All @@ -1698,17 +1698,16 @@ function runErrors(err: unknown, fns: ((err: any) => void)[], owner: Owner | nul

function handleError(err: unknown, owner = Owner) {
const fns = ERROR && owner && owner.context && owner.context[ERROR];
const error = castError(err);
if (!fns) throw error;
if (!fns) throw err;

if (Effects)
Effects!.push({
fn() {
runErrors(error, fns, owner);
runErrors(err, fns, owner);
},
state: STALE
} as unknown as Computation<any>);
else runErrors(error, fns, owner);
else runErrors(err, fns, owner);
}

function resolveChildren(children: JSX.Element | Accessor<any>): ResolvedChildren {
Expand Down
32 changes: 22 additions & 10 deletions packages/solid/src/render/flow.ts
Original file line number Diff line number Diff line change
Expand Up @@ -256,25 +256,37 @@ export function ErrorBoundary(props: {
fallback: JSX.Element | ((err: any, reset: () => void) => JSX.Element);
children: JSX.Element;
}): JSX.Element {
let err;
if (sharedConfig!.context && sharedConfig!.load)
err = sharedConfig.load(sharedConfig.context.id + sharedConfig.context.count);
let err,
hasError = false;
if (sharedConfig.context && sharedConfig.load && sharedConfig.has) {
const key = sharedConfig.context.id + sharedConfig.context.count;
hasError = sharedConfig.has(key);
err = sharedConfig.load(key);
}
const [errored, setErrored] = createSignal<any>(
err,
"_SOLID_DEV_" ? { name: "errored" } : undefined
"_SOLID_DEV_" ? { name: "errored", equals: false } : { equals: false }
);
const pushError = (action: any) => {
hasError = true;
setErrored(() => action);
};
const clearError = () => {
hasError = false;
setErrored();
};
Errors || (Errors = new Set());
Errors.add(setErrored);
onCleanup(() => Errors.delete(setErrored));
Errors.add(clearError as Setter<any>);
onCleanup(() => Errors.delete(clearError as Setter<any>));
return createMemo(
() => {
let e: any;
if ((e = errored())) {
const e = errored();
if (hasError) {
const f = props.fallback;
if ("_SOLID_DEV_" && (typeof f !== "function" || f.length == 0)) console.error(e);
return typeof f === "function" && f.length ? untrack(() => f(e, () => setErrored())) : f;
return typeof f === "function" && f.length ? untrack(() => f(e, clearError)) : f;
}
return catchError(() => props.children, setErrored);
return catchError(() => props.children, pushError);
},
undefined,
"_SOLID_DEV_" ? { name: "value" } : undefined
Expand Down
9 changes: 2 additions & 7 deletions packages/solid/src/server/reactive.ts
Original file line number Diff line number Diff line change
Expand Up @@ -13,18 +13,13 @@ export type Setter<T> = undefined extends T
export type Signal<T> = [get: Accessor<T>, set: Setter<T>];

const ERROR = Symbol("error");
export function castError(err: unknown): Error {
if (err instanceof Error) return err;
return new Error(typeof err === "string" ? err : "Unknown error", { cause: err });
}

function handleError(err: unknown, owner = Owner): void {
const fns = owner && owner.context && owner.context[ERROR];
const error = castError(err);
if (!fns) throw error;
if (!fns) throw err;

try {
for (const f of fns) f(error);
for (const f of fns) f(err);
} catch (e) {
handleError(e, (owner && owner.owner) || null);
}
Expand Down
13 changes: 8 additions & 5 deletions packages/solid/src/server/rendering.ts
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,6 @@ import {
Accessor,
Setter,
Signal,
castError,
cleanNode,
createOwner
} from "./reactive.js";
Expand Down Expand Up @@ -258,6 +257,7 @@ export function ErrorBoundary(props: {
children: string;
}) {
let error: any,
hasError = false,
res: any,
clean: any,
sync = true;
Expand All @@ -275,13 +275,14 @@ export function ErrorBoundary(props: {
return catchError(
() => (res = props.children),
err => {
hasError = true;
error = err;
!sync && ctx.replace("e" + id, displayFallback);
sync = true;
}
);
});
if (error) return displayFallback();
if (hasError) return displayFallback();
sync = false;
return { t: `<!--!$e${id}-->${resolveSSRNode(res)}<!--!$/e${id}-->` };
}
Expand Down Expand Up @@ -368,7 +369,8 @@ export function createResource<T, S>(
let resource: { ref?: any; data?: T } = {};
let value = options.storage ? options.storage(options.initialValue)[0]() : options.initialValue;
let p: Promise<T> | T | null;
let error: any;
let error: any,
hasError = false;
if (sharedConfig.context!.async && options.ssrLoadFrom !== "initial") {
resource = sharedConfig.context!.resources[id] || (sharedConfig.context!.resources[id] = {});
if (resource.ref) {
Expand All @@ -378,7 +380,7 @@ export function createResource<T, S>(
}
}
const read = () => {
if (error) throw error;
if (hasError) throw error;
if (resourceContext && p) resourceContext.push(p!);
const resolved =
options.ssrLoadFrom !== "initial" &&
Expand Down Expand Up @@ -436,7 +438,8 @@ export function createResource<T, S>(
.catch(err => {
read.loading = false;
read.state = "errored";
read.error = error = castError(err);
read.error = error = err;
hasError = true;
p = null;
notifySuspense(contexts);
throw error;
Expand Down
14 changes: 9 additions & 5 deletions packages/solid/test/resource.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -66,10 +66,14 @@ describe("Simulate a dynamic fetch", () => {
expect(value.error).toBeUndefined();
reject("Because I said so");
await Promise.resolve();
expect(error).toBeInstanceOf(Error);
expect(error.message).toBe("Because I said so");
expect(value.error).toBeInstanceOf(Error);
expect(value.error.message).toBe("Because I said so");
// expect(error).toBeInstanceOf(Error);
// expect(error.message).toBe("Because I said so");
// expect(value.error).toBeInstanceOf(Error);
// expect(value.error.message).toBe("Because I said so");
expect(error).toBeTypeOf("string");
expect(error).toBe("Because I said so");
expect(value.error).toBeTypeOf("string");
expect(value.error).toBe("Because I said so");
expect(value.loading).toBe(false);
});
});
Expand Down Expand Up @@ -204,7 +208,7 @@ describe("using Resource with errors", () => {
reject(null);
await Promise.resolve();
expect(value.state === "errored").toBe(true);
expect(value.error.message).toBe("Unknown error");
expect(value.error).toBeNull();
});
});

Expand Down
Loading