From 24e12de95ab6e43fbe99c5cd4e3960cf46d2f905 Mon Sep 17 00:00:00 2001 From: Multinite <145994855+Multinite@users.noreply.github.com> Date: Sat, 7 Dec 2024 06:37:47 +1000 Subject: [PATCH] update(docs): example code to throw errors in database hooks (#790) --- docs/content/docs/concepts/database.mdx | 29 +++++++++++++++++++++++++ 1 file changed, 29 insertions(+) diff --git a/docs/content/docs/concepts/database.mdx b/docs/content/docs/concepts/database.mdx index bf74d15575..12b91aa0f2 100644 --- a/docs/content/docs/concepts/database.mdx +++ b/docs/content/docs/concepts/database.mdx @@ -711,6 +711,35 @@ export const auth = betterAuth({ }) ``` +#### Throwing Errors +If you want to stop the database hook from proceeding, you can throw errors using the `APIError` class imported from `better-auth/api`. + +```typescript title="auth.ts" +import { betterAuth } from "better-auth"; +import { APIError } from "better-auth/api"; + +export const auth = betterAuth({ + databaseHooks: { + user: { + create: { + before: async (user) => { + if(user.isAgreedToTerms === false) { // Your special condition. + // Send the API error. + throw new APIError("BAD_REQUEST", { + message: "User must agree to the TOS before signing up.", + }); + } + return { + data: user + }; + }, + }, + }, + } +}) +``` + + ## Plugins Schema Plugins can define their own tables in the database to store additional data. They can also add columns to the core tables to store additional data. For example, the two factor authentication plugin adds the following columns to the `user` table: