[v4] How to throw an error in a lifecycle hook?

System Information
  • Strapi Version: v4.0.2
  • Operating System: macOS
  • Database: SQLite
  • Node Version: v14
  • NPM Version: v8
  • Yarn Version: v1.22.17

I just see this documentation:

But how to throw an error in a lifecycle hook…?

async beforeUpdate(event) {
  if (condition) {
    // Throw an error here
  }
},

We have no access to a ctx like in the controllers:

I would like to show something like this (with a custom message if possible):

2 Likes

Any news regarding this issue? I’m having the same problem. I would like to return a 400 error and show a friendly message instead of a 500 error.

No news… Still waiting an answer…

I got to do it doing this:

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

...

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

You can check the errors available in @strapi/utils/lib/errors.js

9 Likes

Fabulous !!

that did the trick! thank you very much