Custom error status code with gqlgen + go gin

Custom error status code with gqlgen + go gin


2

Recently I have been updating my GO REST APIs into graphQl API’s and I came across issue where I am unable to customise my status code with gqlgen.

Response I got

Headers

Status Code: 200 OK
{ 
data: null,
errors: [
  {message: "Unauthorized access", path: ["..."]}
]
}

Expected Header

Status Code: 401 UNAUTHORISED

Any help would be really appreciating!

1 Answer
1


5

Assume you have a gqlgen resolver similar to this:

func (r *queryResolver) SecretItems(ctx context.Context, userID string,
    password string) ([]SecretItems, error) {
        // ...
        if !isAuthorized(userID, password) {
                return nil, errors.New("Unauthorized access")
        }
        // ...
}

then the described behavior is expected. Errors should be returned as part of
the response body.

GraphQL is transport agnostic. While it is often served over HTTP, it might be
served over other client-server Protocols as well. Handling errors in the
response body requires no assumptions about the protocol. Hence, you shouldn’t
rely on HTTP status codes.

Handling errors in the response body has another advantage: Assume a request
contains multiple queries. Some of them succeed, some of them fail. Then the
response can contain the result of successful queries under data and errors
related to failed queries under errors.

References:

Possible reason why you expected a 401 status code

The gqlgen docs on
authentication
contain an example
where 401 status code is returned.

Why? This happens in a http handler used as middleware on the chi http server.
The 401 status code is not returned by a GraphQL resolver.



Leave a Reply

Your email address will not be published. Required fields are marked *