使用gqlgen + go gin的自定义错误状态代码 [英] Custom error status code with gqlgen + go gin

查看:126
本文介绍了使用gqlgen + go gin的自定义错误状态代码的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

最近我一直在将我的GO REST API更新到 graphQl API ,我遇到了一个问题无法使用gqlgen自定义我的状态代码.

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.

我得到的答复

标题

Status Code: 200 OK

{ 
data: null,
errors: [
  {message: "Unauthorized access", path: ["..."]}
]
}

期望的标题

Status Code: 401 UNAUTHORISED

任何帮助都会非常感激!

Any help would be really appreciating!

推荐答案

假设您有一个类似于以下代码的 gqlgen 解析器:

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与运输无关.虽然通常是通过HTTP提供服务,但它可能是还可以通过其他客户端-服务器协议来提供服务.处理错误响应主体无需对该协议进行任何假设.因此,您不应该依靠HTTP状态代码.

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.

处理响应正文中的错误还有另一个优点:假设有一个请求包含多个查询.其中有些成功,有些则失败.然后响应可以包含在 data 下成功查询的结果和错误与 errors 下的失败查询有关.

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.

参考文献:

gqlgen 有关身份验证包含一个示例返回401状态代码的地方.

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

为什么?这是在用作http服务器上的中间件的http处理程序中发生的.GraphQL解析器返回的401状态代码 not .

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.

这篇关于使用gqlgen + go gin的自定义错误状态代码的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆