fix: improve error handling for SESSION_EXPIRED and UNAUTHORIZED in TRPC links

This commit is contained in:
Marco Pedone 2026-04-13 16:23:09 +02:00
parent 680d344215
commit c8b11c745e
2 changed files with 26 additions and 7 deletions

View file

@ -9,7 +9,10 @@ export default createNextApiHandler({
createContext: createTRPCContext,
onError: ({ path, error }) => {
if (error.message.startsWith("SESSION_EXPIRED")) {
if (
error.message.startsWith("SESSION_EXPIRED") ||
error.code === "UNAUTHORIZED"
) {
return;
}
if (env.NODE_ENV === "development") {

View file

@ -44,6 +44,7 @@ const errorLink: TRPCLink<AppRouter> = () => {
err,
);
window.location.reload();
return;
}
observer.error(err);
},
@ -60,12 +61,27 @@ export const api = createTRPCNext<AppRouter>({
links: [
errorLink,
loggerLink({
enabled: (opts) =>
(process.env.NODE_ENV === "development" &&
typeof window !== "undefined") ||
(opts.direction === "down" &&
opts.result instanceof Error &&
!opts.result.message.startsWith("SESSION_EXPIRED")),
enabled: (opts) => {
const isDev = process.env.NODE_ENV === "development";
if (opts.direction === "down" && opts.result instanceof Error) {
const isIgnoredError =
opts.result.message.startsWith("SESSION_EXPIRED") ||
opts.result.data?.code === "UNAUTHORIZED";
if (!isIgnoredError) {
return true;
}
if (isDev) {
console.warn("Following error is ignored in production:");
return true;
}
return false;
}
if (isDev) {
return true;
}
return false;
},
}),
splitLink({