System Information
-
Strapi Version: 3.3.1
-
Operating System: MacOS 10.15.7
-
Database: SQLite
-
Node Version: v12.16.1
-
Yarn Version: 1.22.4
So I’m making one of the beforeCreate
callback lifecycle hooks for a model called link
. And I’m looking for a way to possibly stop the creation of data.
For instance, this is an example of what I want to happen ( At the TODO
).
module.exports = {
lifecycles: {
beforeCreate(data) {
if (isNaughtyLink(data.link)) {
// TODO Stop here! dont allow the entry to be made, how'd I do this?
}
},
},
};
module.exports = {
lifecycles: {
beforeCreate(data) {
if (isNaughtyLink(data.link)) {
//throw error here, it will prevent the entry creation
throw new Error('You Shall Not Pass!!!');
}
},
},
};
It is not recommended to throw errors inside lifecycle, as it will throw also the error inside console.
If you have Sentry configured than it will also log the error into sentry.
2 Likes
You can also validate the link
field with regex expression inside Admin UI.
Since throwing an error here causing 500 in response, so how to prevent creating the entry along with sending a custom error like 400 bad request?
Thanks.
Just to improve this answer a bit:
module.exports = {
lifecycles: {
beforeCreate(data) {
if (isNaughtyLink(data.link)) {
//throw error here, it will prevent the entry creation
throw strapi.errors.badRequest('Some message you want to show in the admin UI');
}
},
},
};
3 Likes
errors
does not exist in strapi
object