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');
        	}
        },
      },
    };
2 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);
7 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:

2 Likes

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.

1 Like

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!")
		}
	}
}
3 Likes

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

You can show the list of errors based on your requirement

const { ValidationError } = require("@strapi/utils").errors;
...
if (formValidationError) {
    throw new ForbiddenError("Fill the form");
}

Strapi comes with a lot of error response functions here are they

  HttpError,
  ApplicationError,
  ValidationError,
  YupValidationError,
  PaginationError,
  NotFoundError,
  ForbiddenError,
  PayloadTooLargeError,
  UnauthorizedError,
  PolicyError,

Hi. Were you able to show the error message in the UI?

As @taka says,

Using throw new ApplicationError('Error Message Here'); or for that matter any errors that are exposed by @strapi/utils/libs/errors do work as long as they are not used in the beforeDelete hook.

The beforeDelete hook just shows a default message of “Warning An error occurred during record deletion.”.

Is there anyway to override that?

thanks @taka
i reached to notification component but i want my error msg to be dynamic and provided with the messege written in ApplicationError(""); but in the Notification Component i can’t access this message

Hello there again! Using Strapi v4.10.6. Can’t display error message in beforeDelete hooks, and while throwing Application Error in content-manager/strapi-server.js overwritten update/delete methods. It just shows standart error. Anyone has modern solution to this problem?

I have tried using both of the below

1) throw new ApplicationError('Custom error message')
2) throw new utils.errors.ApplicationError('Custom error message');

but it didn’t workout for me in version v4.9.0.

The admin UI displays Internal server error popup message while in the terminal it displays ApplicationError: Custom error message.

Am I doing something wrong here?

1 Like