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);
|
response.cookies.delete(REFRESH_TOKEN_COOKIE_NAME);
|
||||||
return response;
|
return response;
|
||||||
}
|
}
|
||||||
|
|
||||||
// If refresh token is valid, sign a new access token
|
// If refresh token is valid, sign a new access token
|
||||||
const redirect = req.nextUrl.searchParams.get("redirect");
|
const redirect = req.nextUrl.searchParams.get("redirect");
|
||||||
const destination = onSuccessDashboard
|
const destination = onSuccessDashboard
|
||||||
|
|
|
||||||
|
|
@ -3,9 +3,12 @@ import {
|
||||||
httpSubscriptionLink,
|
httpSubscriptionLink,
|
||||||
loggerLink,
|
loggerLink,
|
||||||
splitLink,
|
splitLink,
|
||||||
|
TRPCClientError,
|
||||||
|
type TRPCLink,
|
||||||
} from "@trpc/client";
|
} from "@trpc/client";
|
||||||
import { createTRPCNext } from "@trpc/next";
|
import { createTRPCNext } from "@trpc/next";
|
||||||
import type { inferRouterInputs, inferRouterOutputs } from "@trpc/server";
|
import type { inferRouterInputs, inferRouterOutputs } from "@trpc/server";
|
||||||
|
import { observable } from "@trpc/server/observable";
|
||||||
import superjson from "superjson";
|
import superjson from "superjson";
|
||||||
import type { AppRouter } from "~/server/api/root";
|
import type { AppRouter } from "~/server/api/root";
|
||||||
|
|
||||||
|
|
@ -19,10 +22,32 @@ const getUrl = () => {
|
||||||
return `${base}/api/trpc`;
|
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>({
|
export const api = createTRPCNext<AppRouter>({
|
||||||
config() {
|
config() {
|
||||||
return {
|
return {
|
||||||
links: [
|
links: [
|
||||||
|
errorLink,
|
||||||
loggerLink({
|
loggerLink({
|
||||||
enabled: (opts) =>
|
enabled: (opts) =>
|
||||||
(process.env.NODE_ENV === "development" &&
|
(process.env.NODE_ENV === "development" &&
|
||||||
|
|
|
||||||
Loading…
Add table
Reference in a new issue