Custom error status code with gqlgen + go gin

流过昼夜 提交于 2021-01-29 07:40:49

问题


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:


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:

  • GraphQL website
  • Specification: Response
  • Hasura: GraphQL vs REST

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.



来源:https://stackoverflow.com/questions/64032675/custom-error-status-code-with-gqlgen-go-gin

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!