Safely handling partial failures in chained hooks (afterChange updates run even when earlier hooks fail) #12637
VinaySanagapalli
started this conversation in
General
Replies: 0 comments
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Uh oh!
There was an error while loading. Please reload this page.
-
Hi everyone,
I’ve got a collection that runs several beforeChange and afterChange hooks. One of the afterChange hooks—pushClientToExternalPortal—writes to an external database. If a later afterChange hook throws an error, the external write has already happened, so my Payload change is rolled back but the external system stays updated. Here’s a trimmed-down, generic version of the setup:
hooks: { beforeChange: [ validatePayloadFields, stampCreatedUpdatedDates, attachTenantContext, requireSignedRequestToken ], afterChange: [ async ({ operation }) => { if (operation === 'update') await purgeCacheTag('clientByDomain'); }, pushClientToExternalPortal, applyDefaultSettings, seedStarterTemplates, createAuxiliaryClientRecord, ensureCoreCollectionsExist ] }
I want the whole chain to act like a single unit:
If any afterChange hook fails, nothing should be pushed to the external portal.
Or, if that’s not possible, at least have a clean way to roll back the external write.
Questions
Is there a Payload-native pattern for wrapping all afterChange hooks in a transaction so they commit or fail together?
Any advice, examples, or best practices would be super helpful. Thanks!
Beta Was this translation helpful? Give feedback.
All reactions