Files
thilalib/src/Layers/trpc/createTRCPErrorMapper.ts
Julien Valverdé 85b6340b97
All checks were successful
Lint / lint (push) Successful in 12s
TRPCContextCreator
2024-09-05 06:07:29 +02:00

68 lines
2.1 KiB
TypeScript

import { Effect, type Cause } from "effect"
const importTRPCServer = Effect.tryPromise({
try: () => import("@trpc/server"),
catch: cause => new Error("Could not import '@trpc/server'. Make sure it is installed.", { cause }),
})
export const createTRCPErrorMapper = importTRPCServer.pipe(Effect.map(({ TRPCError }) =>
<A, E, R>(effect: Effect.Effect<A, E, R>) => Effect.sandbox(effect).pipe(
Effect.catchTags({
Empty: cause => Effect.fail(
new TRPCError({
code: "INTERNAL_SERVER_ERROR",
cause: new TRPCErrorCause(cause),
})
),
Fail: cause => Effect.fail(
cause.error instanceof TRPCError
? cause.error
: new TRPCError({
code: "INTERNAL_SERVER_ERROR",
cause: new TRPCErrorCause(cause),
})
),
Die: cause => Effect.fail(
cause.defect instanceof TRPCError
? cause.defect
: new TRPCError({
code: "INTERNAL_SERVER_ERROR",
cause: new TRPCErrorCause(cause),
})
),
Interrupt: cause => Effect.fail(
new TRPCError({
code: "INTERNAL_SERVER_ERROR",
cause: new TRPCErrorCause(cause),
})
),
Sequential: cause => Effect.fail(
new TRPCError({
code: "INTERNAL_SERVER_ERROR",
cause: new TRPCErrorCause(cause),
})
),
Parallel: cause => Effect.fail(
new TRPCError({
code: "INTERNAL_SERVER_ERROR",
cause: new TRPCErrorCause(cause),
})
),
}),
Effect.tapError(Effect.logError),
)
))
export class TRPCErrorCause<E> extends Error {
constructor(readonly cause: Cause.Cause<E>) {
super()
}
}