lighthouse: Error Handling: Throw a user-friendly authentication exception to include in the response
I am assigning the auth:api middleware on extended Queries and Mutations and I’m not sure how to return a 401 response (or something I can use to differentiate a unauthorized response). This is a screenshot of the error object in the console.

I can see Unauthenticated in the debugMessage, but that won’t show up in production.
Versions “laravel/framework”: “5.7.*”, “nuwave/lighthouse”: “dev-master”,
Here is part of my schema.
#Add Queries to Base Query
extend type Query @middleware(checks: ["auth:api", "verified"]) {
users: [User!]! @all
user(id: ID! @eq): User! @find
}
I was looking into the error handlers, but wasn’t sure how to implement them prior to the middleware. Not sure if there are any tricks to get around this.
Thanks!
About this issue
- Original URL
- State: closed
- Created 5 years ago
- Reactions: 1
- Comments: 16 (8 by maintainers)
Hey,
I implemented another rather simple solution that allows to show the user a nicer error message than
Internal server errorwhen it’s actually anauth:apimiddleware error (similar to the opener I’m doing something liketype Query @middleware(checks: ["auth:api"]) { …).Webonyx’ GraphQL only shows nice messages on errors that implement
GraphQL\Error\ClientAwareand returntrueforisClientSafe(). Since theauth:apimiddleware throws anIlluminate\Auth\AuthenticationExceptionthat doesn’t implement that interface, I created one that does:Then in my Lighthouse ErrorHandler, I check for errors that are instances of the original
AuthenticationExceptionand replace them with myClientAwareAuthenticationException:This creates graphql output like this when an
auth:apierror occurs:Maybe this is helpful for someone else!
Best, Benjamin.
For new comer’s, here’s the updated quick solution:
app/GraphQL/Execution/CustomExtensionErrorHandler.phpwith following codes:app/GraphQL/Exceptions/ClientAwareAuthenticationException.phpwith following codes:composer dump-autoloadin terminal to update our newly created classAnd your’e good to go with nice error output below
I figured it out!
Here is the final product that actually checks if the user is authenticated.
I’m not sure if all of this is 100% necessary, but it is working. This might help someone else.
I would recommend you go for a FieldMiddleware directive instead.
extend typeis especially tricky, since type extensions get compiled away before the query actually executes.