In beforeUpdate lifecycle mehod I'm throwing an error based on some condition. Even though it throws an error it still updates the entry

System Information
  • Strapi Version: V4
  • Operating System: Linux
  • Database: sqlite
  • Node Version: 18
  • NPM Version: 9
  • Yarn Version:

async beforeUpdate(event) {

const { id } = event.params.where;

if (event.params.data.videoUrl) {
  if (!isValidUrl(event.params.data.videoUrl)) {
    throw new errors.ForbiddenError("videoUrl url is not a valid url");
  }
}
if (
  event?.params?.data?.hasOwnProperty("coverImages") &&
  event?.params?.data?.hasOwnProperty("coverImages2")
) {
  if (
    !event?.params?.data?.coverImages?.length &&
    !event?.params?.data?.coverImages2?.length
  ) {
    throw new errors.ForbiddenError("please add a cover image");
  }
}

const entry = await strapi.entityService.findOne("api::class.class", id, {
  populate: { coverImages: true },
});

const selectedCoverImages = entry.coverImages.filter(
  (image) => image.selected
);
if (selectedCoverImages.length !== 1) {
  throw new errors.ForbiddenError(
    "please keep atmost 1 coverImage to be selected true"
  );
}
} 

this is the code i’m working with. here I’m throwing an error if there is no coverImage whose selected field is true. This is throwing an error but it is also updating the database. Can anyone help with this?

Maybe this thread can help you

This thread is suggesting the same thing that I did. It is suggesting to throw and error and in my case I’m already doing that

Have you tried using this

throw new Error('Error message');

instead of your code

 throw new errors.ForbiddenError("please add a cover image");

This is throwing error on terminal. I wanted the error to be shown on UI that’s why using this: throw new errors.ForbiddenError(“please add a cover image”);

Also even though it’s throwing error on terminal it is still updating the entry.

The main issue is I’m trying to update a component here from this model.

Hmmm, I see :thinking:
Haven’t got any more solution to break the update execution using hooks.

Wait until someone comes up with a solution.

@Sameer_Srivastava, I have a similar error.

For my usecase I wanted a more refined “unique” functionality. So, using the beforeUpdate I make a db query and based on some if statements I throw an error or continue with the update.

What I have noticed is that beforeUpdate function runs 2 times even though I only click the Save button in the Admin UI once.

The first time my if statements are OK so my entity is updating correctly.

The second time the event.params.data is missing the id field on which I make some checks. Because it is undefined I get the ApplicationError in my Admin UI but it is not correct and my admins get confused.

Maybe it’s something similar to you?