Is there a way to stop deleting / updating a record in lifecycle with an error message in backend?

System Information
  • Strapi Version: 4.1.12
  • Operating System:
  • Database: PostgersQL
  • Node Version: 16
  • NPM Version:
  • Yarn Version:

Previously I used lifecycle hook beforeDelete to stop admin user from deleting some specific records and return an error message,. I did it by throwing an error with a custom error.message, I could see the message in the backend which is pretty neat. However after I upgraded to 4.1.x (forgot when it started not working), it only returns a fixed error message: Warning: An error occurred during record deletion.. So for now, is there still a way to stop deletion / update in beforeDelete / beforeUpdate hook, and also being able to send admin user a custom error message?
Many thanks!

I would rather use a middleware or policy for this.

I couldn’t make it work for the custom msg, instead found a hack for my use case :
‘Can’t contribute to CMS if the dates are before 4 days from now’

Object ‘data’ is not findable on beforeDelete (Strapi 4.5.5)
What’s given is the ID. Si i search the DB with the ID, check the date and throw error to cancel delete.

import { daysDifference } from '../../../../shared/utils'
import utils from '@strapi/utils'
const { ForbiddenError } = utils.errors

// Throw error does not work (it displays another error msg in frontend app Strapi),
// that's why i've set the beginning date to false : throws UI error 'invalid date'

const windowOfDaysWithoutModification = 3

export default {
  beforeCreate(event) {
    const dateAfterThreeDays = daysDifference(windowOfDaysWithoutModification, event.params.data.date)
    if (!dateAfterThreeDays) {
      event.params.data.date = false
    }
  },
  beforeUpdate(event) {
    const dateAfterThreeDays = daysDifference(windowOfDaysWithoutModification, event.params.data.date)
    if (!dateAfterThreeDays) {
      event.params.data.date = false
    }
  },
  async beforeDelete(event) {
    let item = null
    console.log(event)
    try {
      item =
        (await strapi.db.query('api::pricing.pricing').findOne({
          select: ['date'],
          where: { id: event.params.where.id }
        }))
    } catch (error) {
      console.log('error in db fetch of wanted item. Action : delete')
    }

    const dateAfterThreeDays = daysDifference(windowOfDaysWithoutModification, item.date)
    console.log(dateAfterThreeDays)
    if (!dateAfterThreeDays) {
      throw new ForbiddenError(
        'Impossible de supprimer une offre si la date de début ou de fin est dans 3 jours ou moins'
      )
    }
  }
}
1 Like