T
TanStack3y ago
extended-salmon

queryClient.ensureQuery and throwing to ErrorBoundary

Is there a way to make queries throw other things than Errors? I'm using queryClient.ensureQuery with React Router's loader like this:
async function getFoo(foo: string) {
const query = {
queryKey: ['fooKey', foo],
queryFn: async () => {
const response = await fetch(`api.example.com/${foo}`);
if (!response.ok) {
throw response;
}
return await response.json();
},
useErrorBoundary: true,
};

return await queryClient.ensureQueryData(query);
}

export async function loader({params}) {
const { fooId } = params;
const foo = getFoo(fooId);
return foo;
}
async function getFoo(foo: string) {
const query = {
queryKey: ['fooKey', foo],
queryFn: async () => {
const response = await fetch(`api.example.com/${foo}`);
if (!response.ok) {
throw response;
}
return await response.json();
},
useErrorBoundary: true,
};

return await queryClient.ensureQueryData(query);
}

export async function loader({params}) {
const { fooId } = params;
const foo = getFoo(fooId);
return foo;
}
I expected to catch this in my React Router ErrorComponent, but it's not an Error object so it's ignored and ensureQuery returns.
7 Replies
variable-lime
variable-lime3y ago
throw - JavaScript | MDN
The throw statement throws a user-defined exception. Execution of the current function will stop (the statements after throw won't be executed), and control will be passed to the first catch block in the call stack. If no catch block exists among caller functions, the program will terminate.
correct-apricot
correct-apricot3y ago
not sure, maybe its a router thing that it doesn't catch things that aren't errors? I would say its discouraged to throw things that are non-errors though. You could create your own error subclass and attach the response to it in v5, we'll also default the error type to Error because everybody only throws errors and having unknown is just a huge burden for most users
extended-salmon
extended-salmonOP3y ago
Throwing Responses from the loader and action functions and catching them in the route ErrorComponent/errorElement is one of the things Michael and Ryan have brought to React Router from Remix in version 6. Throwing a new Response in the loader or a new Error in the query renders my ErrorComponent.
extended-salmon
extended-salmonOP3y ago
This is rather unhelpful. What is your point? I know the difference between the return and exception flows. Exceptions are not synonymous with errors. Though it is unconventional to throw other things than errors, it's not the sole intent of the exception program flow.
variable-lime
variable-lime3y ago
Like Dominik said: throw an error… written by MDN
extended-salmon
extended-salmonOP3y ago
Their reasoning doesn't apply in this case, and it's not an answer to my question.
variable-lime
variable-lime3y ago
Most times people ask the wrong question….

Did you find this page helpful?