mykola
mykola
SSolidJS
Created by mykola on 8/17/2024 in #support
handling (http) errors with createResource
I don't understand how to get hold of the error when using the tutorial examples of fetching REST data. The error is always either empty, or not callable to me ("solid-js": "^1.8.11"). If I take the example from the documentation here and make it work. I shows the fetched data OK, but doesn't handle http404's. OK, I modify the fetchUser function to throw on non-ok:
const fetchUser = async (id) => {
const response = await fetch(`https://swapi.dev/api/people/${id}/`);
if (!response.ok) {
throw Error(`Response not ok ${response.status}`);
}
return response.json();
};

function App() {
const [userId, setUserId] = createSignal();
const [user] = createResource(userId, fetchUser);

return (
<div>
<input
type="number"
min="1"
placeholder="Enter Numeric Id"
onInput={(e) => setUserId(e.currentTarget.value)}
/>
<Show when={user.loading}>
<p>Loading...</p>
</Show>
<Switch>
<Match when={user.error}>
<span>Error: {user.error()}</span>
</Match>
<Match when={user()}>
<div>{JSON.stringify(user())}</div>
</Match>
</Switch>
</div>
);
}
const fetchUser = async (id) => {
const response = await fetch(`https://swapi.dev/api/people/${id}/`);
if (!response.ok) {
throw Error(`Response not ok ${response.status}`);
}
return response.json();
};

function App() {
const [userId, setUserId] = createSignal();
const [user] = createResource(userId, fetchUser);

return (
<div>
<input
type="number"
min="1"
placeholder="Enter Numeric Id"
onInput={(e) => setUserId(e.currentTarget.value)}
/>
<Show when={user.loading}>
<p>Loading...</p>
</Show>
<Switch>
<Match when={user.error}>
<span>Error: {user.error()}</span>
</Match>
<Match when={user()}>
<div>{JSON.stringify(user())}</div>
</Match>
</Switch>
</div>
);
}
the rendering gets broken because the user.error() isn't a function šŸ¤”
Uncaught (in promise) TypeError: user.error is not a function
Uncaught (in promise) TypeError: user.error is not a function
When I replace user.error() with the typeOf and JSON.stringify, they show an empty object {}.
<Match when={user.error}>
<span>Error: {typeof(user.error)} {JSON.stringify(user.error)}</span>
</Match>
<Match when={user.error}>
<span>Error: {typeof(user.error)} {JSON.stringify(user.error)}</span>
</Match>
ā“ What do I do wrong, and how to get the resource errors reported properly? I tried Promised.reject(new Error(...)) and axios.get with no change in behavior. Playground example: https://playground.solidjs.com/anonymous/3b5dbdc3-c242-4d24-8468-f7b5c98509ed
9 replies