Throw Error message in lifecycle hook doesnt change the error message display in the UI

System Information
  • Strapi Version: 3.3.4
  • Operating System: macOS
  • Database: SQLlite
  • Node Version: 12.18
  • NPM Version:
  • Yarn Version:

Hi,
I was trying to add some custom validation logic in the “beforeCreate” lifecycle hook, but I was not able to customize the error message displayed in the UI , it is always returning the default one.
I tried to throw a “new Error”(“custom message”)" but no luck there.
Is it something doable ?

B.R

I did it in this way:

module.exports = {
      lifecycles: {
        beforeCreate(data) {
        	if (someCondition(data)) {
        		// throw error here, it will prevent the entry creation
        		throw strapi.errors.badRequest('Some message you want to show in the admin UI');
        	}
        },
      },
    };
4 Likes

This is great! Works like a charm!
It would be great if this was documented in the official Strapi documentation.
@piwi maybe you could add this to the documentation API Reference - Strapi Developer Documentation? thanks!

Thanks for the ping @meck93 ! :slight_smile:
Lifecycle hooks and error handling will be fully redesigned for Strapi v4, so the documentation will be updated accordingly.

However, in the meantime, this is something I can add to the Backend Customization > Models > Lifecycle hooks documentation.

2 Likes

That doesn’t seems to work anymore in Strapi v4, I can’t find anything about this in the v4 docs.
Does anyone have a clue on how to throw custom errors to the backend UI ?

Thanks !

I was able to get an error to appear by adding a global middleware since Strapi v4 allows error handling with the ctx object. Error handling - Strapi Developer Docs

module.exports = (config, { strapi }) => {
  // Add your own logic here.
  return async (ctx, next) => {
    
    strapi.log.info('In page-adjuster middleware.');
    
    // check that the page content is being changed
    if ( (ctx.request.method === 'PUT' || ctx.request.method === 'POST') &&
      ctx.request.url.includes('/content-manager/collection-types/api::page.page')) {
      // check if the slug is restrictive
      if (ctx.request.body.slug === 'test') {
        strapi.log.info('restrictive slug');
        return ctx.badRequest('Restricted slug: Choose a different slug', { slug: ctx.request.body.slug })
      }
    }
    await next();
  };
};

Hi @piwi
What would be the equivalent solution in Strapi v4.0 of the elegant code snippet that @christianguevara has proposed (cf. below) ?
Thanks & Regards,

module.exports = {
      lifecycles: {
        beforeCreate(data) {
        	if (someCondition(data)) {
        		// throw error here, it will prevent the entry creation
        		throw strapi.errors.badRequest('Some message you want to show in the admin UI');
        	}
        },
      },
2 Likes

Strapi v4

const { ApplicationError } = require(’@strapi/utils’).errors;

throw new ApplicationError('Not found',4xx);
5 Likes

Thanks a lot @taka : it’s perfect !

Thanks @taka :slight_smile:
However, does anyone know how to customize the error message in the error snackbar ?
When using @taka solution in a lifecycle hook, the error is thrown as expected but the error message in the snackbar is as usual: “Warning Alert: Bad request”… Is there a way to customize this message to give more details to the user ? I can’t find a solution for strapi v4 :confused:

for custom notification message, Maybe you need to override Notification component in admin
.cache/admin/src/components/Notifications/Notification/index.js

Thanks @Hartecode, this definitely works. However, it would so much better if we could do this within the lifecycles someway.

I’ve tried the other solution provided by @taka but that just throws an internal error message in the Admin. Maybe I’m doing something wrong.

Here is my lifecycles.js (this is just a PoC) that works (Strapi v4.1.5).
A warning is shown with my message.

What I would really like to do is to show the error message at the specific field - but that seems a bit far fetched :slight_smile:

const { ApplicationError } = require("@strapi/utils").errors

module.exports = {
	beforeUpdate(event) {
		const { data } = event.params
		console.log("product-beforeUpdate", data)
		if (data.price === null || data.price === 0 || data.price === "") {
			throw new ApplicationError("Product Price needs to be set!")
		}
	}
}
1 Like

strapi.errors.badRequest is able to change notification message in single delete of file upload but it doesn’t work in multi delete. Notification msg is not changing and confirm button upload is not getting removed