Skip to content

Commit d03054e

Browse files
docs: add info about custom errors via APIError to hooks overview (#13047)
<!-- Thank you for the PR! Please go through the checklist below and make sure you've completed all the steps. Please review the [CONTRIBUTING.md](https://github.com/payloadcms/payload/blob/main/CONTRIBUTING.md) document in this repository if you haven't already. The following items will ensure that your PR is handled as smoothly as possible: - PR Title must follow conventional commits format. For example, `feat: my new feature`, `fix(plugin-seo): my fix`. - Minimal description explained as if explained to someone not immediately familiar with the code. - Provide before/after screenshots or code diffs if applicable. - Link any related issues/discussions from GitHub or Discord. - Add review comments if necessary to explain to the reviewer the logic behind a change --> ### What? I was searching for info on how to return custom errors in hooks and only came upon this discord answer by Dan Ribbons: https://payloadcms.com/community-help/github/customize-rest-api-response-in-collection-hooks ### Why? I think this info should be in the docs. ### How? This PR adds a `Cusom Error Messages` section to the hooks-overview page, detailing the usage of `APIError` as proposed by Dan Ribbons in the above discord answer. Co-authored-by: Paul Popus <paul@payloadcms.com>
1 parent 911f059 commit d03054e

1 file changed

Lines changed: 16 additions & 0 deletions

File tree

docs/hooks/overview.mdx

Lines changed: 16 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -127,6 +127,22 @@ const afterChange = ({ doc }) => {
127127

128128
Hooks are only triggered on the server and are automatically excluded from the client-side bundle. This means that you can safely use sensitive business logic in your Hooks without worrying about exposing it to the client.
129129

130+
## Custom Error Messages
131+
132+
You might want to return custom error messages in the API or admin panel in your hooks, if an operation cannot be performed - e.g. if a rate limit was exceeded. For this you can leverage the `APIError` class like this:
133+
134+
```ts
135+
import { APIError, type CollectionBeforeChangeHook } from 'payload'
136+
137+
const beforeChangeHook: CollectionBeforeChangeHook = async ({ data }) => {
138+
...
139+
if (rateLimitExceeded) {
140+
throw new APIError('You have sent too many requests', 429)
141+
}
142+
return data
143+
}
144+
```
145+
130146
## Performance
131147

132148
Hooks are a powerful way to customize the behavior of your APIs, but some hooks are run very often and can add significant overhead to your requests if not optimized.

0 commit comments

Comments
 (0)