Handling Typed Errors in JWT Verification with Functional Programming in TypeScript

Hello folk,
I try to find an elegant solution to type Error from popular librairy. For example here : jsonwebtoken (jwt).
.verify of jwt could throw a typed VerifyError

The question here is how can I use this typed error when I'm using jwt with Effect.try ?

const verifyTokenEffect = (secret: string) => (token: string): T.Effect<string | JwtPayload, Error, never> =>
  T.try(() => jwt.verify(token, secret)).pipe(T.mapError(e => new Error(e.message)))


Here with a catch clause but similar to try ... catch
const verifyTokenEffect = (secret: string) => (token: string): T.Effect<string | JwtPayload, VerifyErrors, never> =>
  T.try({
    try: () => jwt.verify(token, secret),
    catch: error => error as VerifyErrors
  })
`

In FP, I'm using something like that, the error is "forced" cast to the typed I gave
const verifyTokenEither = (secret: string) => (token: string): Either<string | JwtPayload, VerifyErrors> =>
  myFpMonad.try<string | JwtPayload, VerifyErrors>(() => jwt.verify(token, secret))


Maybe, I'm doing wrong.

If not ,my point of vue : If we're knowing what kind of errors are thrown from some external / legacy code (jsonwebtoken, zod, Axios ...), we could have the possibility to forced the cast on the Effect.try call.

What do you thing?
Was this page helpful?