Enhance API error handling: add errorLink to handle UNAUTHORIZED errors and reload the page
This commit is contained in:
parent
709ac307e1
commit
e20731e027
2 changed files with 25 additions and 1 deletions
|
|
@ -125,7 +125,6 @@ const refreshAuthToken = async (
|
|||
response.cookies.delete(REFRESH_TOKEN_COOKIE_NAME);
|
||||
return response;
|
||||
}
|
||||
|
||||
// If refresh token is valid, sign a new access token
|
||||
const redirect = req.nextUrl.searchParams.get("redirect");
|
||||
const destination = onSuccessDashboard
|
||||
|
|
|
|||
|
|
@ -3,9 +3,12 @@ import {
|
|||
httpSubscriptionLink,
|
||||
loggerLink,
|
||||
splitLink,
|
||||
TRPCClientError,
|
||||
type TRPCLink,
|
||||
} from "@trpc/client";
|
||||
import { createTRPCNext } from "@trpc/next";
|
||||
import type { inferRouterInputs, inferRouterOutputs } from "@trpc/server";
|
||||
import { observable } from "@trpc/server/observable";
|
||||
import superjson from "superjson";
|
||||
import type { AppRouter } from "~/server/api/root";
|
||||
|
||||
|
|
@ -19,10 +22,32 @@ const getUrl = () => {
|
|||
return `${base}/api/trpc`;
|
||||
};
|
||||
|
||||
const errorLink: TRPCLink<AppRouter> = () => {
|
||||
return ({ next, op }) => {
|
||||
return observable((observer) => {
|
||||
const unsubscribe = next(op).subscribe({
|
||||
next: observer.next,
|
||||
error(err) {
|
||||
if (
|
||||
err instanceof TRPCClientError &&
|
||||
err.data?.code === "UNAUTHORIZED"
|
||||
) {
|
||||
window.location.reload();
|
||||
}
|
||||
observer.error(err);
|
||||
},
|
||||
complete: observer.complete,
|
||||
});
|
||||
return unsubscribe;
|
||||
});
|
||||
};
|
||||
};
|
||||
|
||||
export const api = createTRPCNext<AppRouter>({
|
||||
config() {
|
||||
return {
|
||||
links: [
|
||||
errorLink,
|
||||
loggerLink({
|
||||
enabled: (opts) =>
|
||||
(process.env.NODE_ENV === "development" &&
|
||||
|
|
|
|||
Loading…
Add table
Reference in a new issue