'Customize Strapi default permission error return
Is there a way to edit the default error return by Strapi for permission / token error?
For example, in roles & permissions under Public role, I uncheck the route for send-email-confirmation. If I use postman and try doing localhost:1337/auth/send-email-confirmation, I would get such error return
{
"statusCode": 403,
"error": "Forbidden",
"message": "Forbidden"
}
I believe this is the default middleware / policy I know where I can get the default send-email-confirmation controller and edit it, but that is only if Roles & Permissions are enabled / checked inside public role.
Same as if a route requires headers of Authorization token but if it is not provided, a default error will be given again which I am not able to find where to customize it.
I don't seem to find it inside strapi documentation or maybe I am using the wrong key words to search.
Thanks in advance for any suggestions + advices.
Solution 1:[1]
Create custom error response files
In folder config/functions/responses/, create corresponding files with relevant filename matching the error code. Inside you can inspect the event and return a custom response. This works for me using Strapi 3.6.8. I'm not sure of latest Strapi. Here's an older doc page with error codes as reference.
Create files in this format for a variety of error codes...
Examples:
config/functions/responses/404.js
'use strict'
module.exports = async (ctx) => {
// Do other stuff
console.log("404 response is: %O, ctx)
// Return a specific error format (e.g. 'notFound') with your own custom message
return ctx.notFound('My custom 404 message')
}
config/functions/responses/403.js
'use strict'
module.exports = async (ctx) => {
// Do other stuff
console.log("403 response is: %O, ctx)
// Return a specific error format (e.g. 'forbidden') with your own custom message
return ctx.forbidden('My custom 403 message')
}
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | MarsAndBack |
