How can I make a "error middleware"?

Hi guys. So, I have the back-end config of better-auth and the front-end client.
The thing is, I need to format the errors of the better auth to normalize them to the default error pattern that my back-end provides, and for such, I needed some kind of error middleware of the better auth in the back-end.

I tried the following in the back-end config:

export const auth = betterAuth({
  onAPIError: {
    throw: true,
    onError(error, ctx) {
      console.error('Auth error:', error)
      // handleBetterAuthError(error)

      throw Exception.new({
        code: Code.UNAUTHORIZED_ERROR,
        overrideMessage: 'No sign in found.',
      })
    },
  },
  database: prismaAdapter(prisma, {
    provider: 'postgresql',
  }),
  emailAndPassword: {
    enabled: true,
    minPasswordLength: 8,
    maxPasswordLength: 128,
  },
  trustedOrigins: [env.APP_URL],
  baseURL: env.BETTER_AUTH_URL,
  socialProviders: {
    google: {
      clientId: env.GOOGLE_CLIENT_ID,
      clientSecret: env.GOOGLE_CLIENT_SECRET,
      redirectURI: env.GOOGLE_REDIRECT_URL,
      prompt: 'select_account',
    },
  },
})


But still, in the FE, I get the original better auth error. It is like the function call on the FE just ignores that "onError" of the BE. What I expected is that every error would pass there and then get throw again to its final version on the FE
image.png
Was this page helpful?