diff --git a/dev/bun/_auth.ts b/dev/bun/_auth.ts index 4486251e25..fa396b167c 100644 --- a/dev/bun/_auth.ts +++ b/dev/bun/_auth.ts @@ -1,5 +1,6 @@ import { betterAuth } from "better-auth"; import { prismaAdapter } from "better-auth/adapters/prisma"; +import { APIError } from "better-auth/api"; import { twoFactor } from "better-auth/plugins"; export const auth = betterAuth({ @@ -11,3 +12,10 @@ export const auth = betterAuth({ ), plugins: [twoFactor()], }); + +try { + await auth.api.signOut(); +} catch (e) { + if (e instanceof APIError) { + } +} diff --git a/docs/content/docs/concepts/api.mdx b/docs/content/docs/concepts/api.mdx index f71a1a7265..3eec6f35a0 100644 --- a/docs/content/docs/concepts/api.mdx +++ b/docs/content/docs/concepts/api.mdx @@ -42,3 +42,24 @@ await auth.api.getSession({ Unlike the client, the server needs the values to be passed as an object with the key `body` for the body, `headers` for the headers, and `query` for the query. + +## Error Handling + +When you call an API endpoint in the server, it will throw an error if the request fails. You can catch the error and handle it as you see fit. The error instance is an instance of `APIError`. + +```ts title="server.ts" +import { APIError } from "better-auth/api"; + +try { + await auth.api.signInEmail({ + body: { + email: "", + password: "" + } + }) +} catch (error) { + if (error instanceof APIError) { + console.log(error.message, error.status) + } +} +``` diff --git a/packages/better-auth/src/api/index.ts b/packages/better-auth/src/api/index.ts index ef0adc9b87..6d6a9804aa 100644 --- a/packages/better-auth/src/api/index.ts +++ b/packages/better-auth/src/api/index.ts @@ -254,3 +254,4 @@ export const router = ( export * from "./routes"; export * from "./middlewares"; export * from "./call"; +export { APIError } from "better-call";