Error Handling / Throw error in Strapi 4.0

Viewed 524

in Strapi 4.0, i want to validate the input before saving. So i created lifecycles.js file as per the documentation and added the code:

module.exports = {
    beforeCreate(event) {
         //validation login here;
         if (!valid) {
             throw strapi.errors.badRequest('Invalid Entry');
        }
    },
}
 

How ever throw strapi.errors.badRequest('Invalid Entry'); is giving an error :

Cannot read property 'badRequest' of undefined

My guess is the Strapi v4 changed it from version 3. I looked everywhere but couldn't find a solution.

Any idea on how to handle error in lifecycles.js?

2 Answers

I had a similar situation with a forbidden error. I got to do it importing a class from @strapi/utils/lib/errors.js

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

...

if (!authorized) {
  throw new ForbiddenError(errorMessage);
}

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,
Related