Simplify your stack and build anything. Or everything.
Build tomorrow’s web with a modern solution you truly own.
Code-based nature means you can build on top of it to power anything.
It’s time to take back your content infrastructure.

Throw error to user when using `onChange` hook

default discord avatar
plainnnlast year
15

I'm trying to ensure a block is always first in the block list, is there a way to throw a custom error when it's incorrect? Currently this code just logs out to the console, but i want to show an error to the user...



    beforeChange: [
      async ({ data }): Promise<any> => {
        // Check the order of the blocks, if homepageHeroSlides is not first, throw an error
        const { blocks } = data;
        const homepageHeroSlidesIndex = blocks.findIndex(
          (block) => block.blockType === 'homepageHeroBlock'
        );
        if (homepageHeroSlidesIndex !== 0) {
          throw new Error('Homepage Hero Slides must be the first block');
        }
      },
    ],
  • discord user avatar
    jesschow
    last year

    Hi @Plain - try replacing the line 'throw new Error(...)' with the following:



    toast.error('Homepage Hero Slides must be the first block')
  • default discord avatar
    plainnnlast year

    @jesschow thanks for the reply, unfortunately that doesn't seem to do anything, it just saves like normal

  • discord user avatar
    jesschow
    last year

    Is this a collection or field

    beforeChange

    hook? Did you import

    import { toast } from 'react-toastify'

    ?

  • default discord avatar
    plainnnlast year

    It's actually a

    GlobalConfig

    hook, and yeah, imported toast correctly 👌



    const Homepage: GlobalConfig = {
      slug: 'homepage',
      access: {
        read: (): boolean => true,
      },
      hooks: {
        beforeChange: [
          async ({ data, global, originalDoc, req }): Promise<any> => {
            const { blocks } = data;
            const homepageHeroSlidesIndex = blocks.findIndex(
              (block) => block.blockType === 'homepageHeroBlock'
            );
    
            console.log('homepageHeroBlockIndex', homepageHeroSlidesIndex);
    
            if (homepageHeroSlidesIndex !== 0) {
              toast.error('Homepage Hero Slides must be the first block');
              console.log('Homepage Hero Slides must be the first block');
            }
          },
        ],
      },
    // other stuff here
  • discord user avatar
    jesschow
    last year

    Odd, you can throw a

    toast.error

    directly from collections or custom components - not sure why this doesn't work for globals...



    Instead, give this a go

    import { APIError } from 'payload/errors'

    and then throw your error like this

    throw new APIError('Homepage Hero Slides must be the first block')
  • default discord avatar
    plainnnlast year

    @jesschow hmm, that works in the console, and shows a 'Something went wrong' toast error, but i want it to describe the issue to the user...

    [12:05:52] ERROR (payload): APIError: Homepage Hero Slides must be the first block
    image.png
  • discord user avatar
    jesschow
    last year

    Hmm that should allow you to output your custom error message... are there any other errors in your console?

    Screenshot_2023-11-07_at_12.09.02_PM.png
    Screenshot_2023-11-07_at_12.15.18_PM.png
  • default discord avatar
    plainnnlast year

    Just a 500 which appears when trying to save



    @jesschow after a bit of googling, I needed to use


       throw new APIError(
                'Hompage Hero Slides must be the first block',
                400,
                undefined,
                true
              );
    image.png
  • discord user avatar
    jesschow
    last year

    Oic it needed to be extended. Is the error displaying the custom message correctly now?

  • default discord avatar
    steadysnail11 months ago

    @jesschow Since updating to v2 none of the "APIErrors" I'm throwing are being displayed to the client. Before I was able to:


    import APIError from "payload/dist/errors/APIError";
    
    throw new APIError("Customer Error Message")

    And "Custom Error Message" would be displayed on the client. With v1 using the above format I was able to successfully throw APIErrors with custom messages from both collection and field hooks.



    Now I get the "Something Went Wrong" generic message and a 500 error in the client console. In the server console I am seeing the correct custom error message



    I have copy and pasted the import statement and invocation from the above comments and I still get the same behavior.



    Any idea what could be causing this? Also, is there a similar solution for success toast messages?

  • default discord avatar
    plainnn11 months ago

    @steadysnail I have found this same issue, but only when calling a hook like



    hooks: {
      beforeChange: [ aHookTitleHere ]
    }


    but when doing



      hooks: {
        beforeChange: [
          async ({ data }): Promise<any> => {
               throw new APIError(
                'A custom error',
                400,
                undefined,
                true
              );
          }
      ]
    }


    It works fine

  • default discord avatar
    steadysnail11 months ago

    @Plain Interesting... Some of the hooks I'm calling APIError from are 100-200 lines long. Really dont want to have to inline those...

  • default discord avatar
    plainnn11 months ago

    @steadysnail I'm in the same boat, its definitely not ideal



    Still looking for a fix for this, but just realised in this example:

    https://payloadcms.com/community-help/discord/is-there-a-way-to-create-a-toast-error-message-on-the-frontend-from-within-a-doc-or-field-hook

    The import is

    import { APIError } from 'payload/errors'

    rather than

    import APIError from 'payload/dist/errors/APIError'

    Might be worth a shot? @steadysnail

  • default discord avatar
    steadysnail11 months ago

    @Plain Thanks, I'll give it a shot when I get a chance over the next few days and let you know how it goes!



    @Plain That got it working for me! Thanks! Much appreciated.

  • default discord avatar
    jamesryandev10 months ago

    Thank you both! this answered my query as upgrading to v2 also broke my hook error messages

Star on GitHub

Star

Chat on Discord

Discord

online

Can't find what you're looking for?

Get dedicated engineering support directly from the Payload team..