Strapi (v4) GraphQL Errors
With GraphQL errors can be tough. Make graphQL a plugin and they can get worse. This helps explain how to make GraphQL errors more understandable in Strapi V4.
Kenny H.
Implementing Strapi Errors in GraphQL
Strapi provides a set of built-in errors that you can use in your application. These errors include HttpError, ForbiddenError, UnauthorizedError, ApplicationError, and ValidationError. You can use these errors in your GraphQL resolvers to handle different error situations.
_This guide is intended for you to add these errors to your cusom GQL resolvers. This does not apply to the built in resolvers that come with content types _
Step 1: Import the Errors
First, you need to import the errors from Strapi's utils. You can do this at the top of your resolver file:
const {
HttpError,
ForbiddenError,
UnauthorizedError,
ApplicationError,
ValidationError,
} = require("@strapi/utils").errors;
Alternatively...
import utils from "@strapi/utils";
const {
HttpError,
ForbiddenError,
UnauthorizedError,
ApplicationError,
ValidationError,
} = utils.errors;
Step 2: Use the Errors in Your Resolvers
Next, you can use these errors in your GraphQL resolvers. In Strapi V4 you do this in your src/index
file. In this example, UnauthorizedError is thrown if the user is not logged in, and ForbiddenError is thrown if the user does not have the necessary permissions.
import utils from "@strapi/utils";
const {
HttpError,
ForbiddenError,
UnauthorizedError,
ApplicationError,
ValidationError,
} = utils.errors;
export default {
register(/*{ strapi }*/) {
const extensionService = strapi.service("plugin::graphql.extension");
extensionService.use(({ strapi }) => ({
typeDefs: print(schema),
resolvers: {
myResolver: async (parent, args, context, info) => {
// Some logic here...
if (!context.state.user) {
throw new UnauthorizedError("You must be logged in to do that");
}
if (!userHasPermission(context.state.user)) {
throw new ForbiddenError("You do not have permission to do that");
}
// More logic here...
},
},
}));
}
}
Not Working?
- "All the errors are the same INTERNAL_SERVER_ERRORS"
The way that Strapi compares Error types for GraphQL requires them to be imported from the same version of the depencecy. To fix it you will need to tell your package manager to resolve the same version of
@strapi/utils
everywhere in the project. The folowing is an example using yarn.
"resolutions": {
"@strapi/utils": "4.10.4"
},
By following these steps, you can implement Strapi's built-in errors in your GraphQL resolvers. This allows you to handle different error situations in a consistent and predictable way.