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 }) =>
(effect: Effect.Effect) => 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 extends Error {
constructor(readonly cause: Cause.Cause) {
super()
}
}