Nextor2k
Nextor2k
TtRPC
Created by justindgm on 11/28/2023 in #❓-help
Vanilla Client Error Handling
is there a better way?
14 replies
TtRPC
Created by justindgm on 11/28/2023 in #❓-help
Vanilla Client Error Handling
then you can use like this:
const result = await withClient((api) => api.auth.session.query());
const result = await withClient((api) => api.auth.session.query());
14 replies
TtRPC
Created by justindgm on 11/28/2023 in #❓-help
Vanilla Client Error Handling
@BillyBob Maybe its too late, was trying to sort it out, best way I could do it was the following:
import { TRPCClientError } from '@trpc/client';
import { httpBatchLink, createTRPCProxyClient } from '@trpc/client';
import type { AppRouter } from '@poseidon/proto-onboard-server/trpc';
import { getServerUrl } from './utils';
import { redirect } from 'next/navigation';
import { getSession } from './auth';

export function isTRPCClientError(
cause: unknown,
): cause is TRPCClientError<AppRouter> {
return cause instanceof TRPCClientError;
}

export const trpc = createTRPCProxyClient<AppRouter>({
links: [
httpBatchLink({
url: `${getServerUrl()}/trpc`,
fetch(url, options) {
return fetch(url, {
...options,
credentials: 'include',
});
},
async headers() {
const session = await getSession();
if (session?.user.accessToken) {
return {
Authorization: `Bearer ${session.user.accessToken}`,
};
}
return {};
},
}),
],
});

export const withClient = <T>(fn: (api: typeof trpc) => Promise<T>) => {
return fn(trpc).catch((cause: unknown) => {
if (isTRPCClientError(cause)) {
if (cause.data?.code === 'UNAUTHORIZED') {
redirect('/en/overview/session-expired');
}
}
throw cause;
});
};
import { TRPCClientError } from '@trpc/client';
import { httpBatchLink, createTRPCProxyClient } from '@trpc/client';
import type { AppRouter } from '@poseidon/proto-onboard-server/trpc';
import { getServerUrl } from './utils';
import { redirect } from 'next/navigation';
import { getSession } from './auth';

export function isTRPCClientError(
cause: unknown,
): cause is TRPCClientError<AppRouter> {
return cause instanceof TRPCClientError;
}

export const trpc = createTRPCProxyClient<AppRouter>({
links: [
httpBatchLink({
url: `${getServerUrl()}/trpc`,
fetch(url, options) {
return fetch(url, {
...options,
credentials: 'include',
});
},
async headers() {
const session = await getSession();
if (session?.user.accessToken) {
return {
Authorization: `Bearer ${session.user.accessToken}`,
};
}
return {};
},
}),
],
});

export const withClient = <T>(fn: (api: typeof trpc) => Promise<T>) => {
return fn(trpc).catch((cause: unknown) => {
if (isTRPCClientError(cause)) {
if (cause.data?.code === 'UNAUTHORIZED') {
redirect('/en/overview/session-expired');
}
}
throw cause;
});
};
14 replies