如何正确读取Golang Oauth2的错误


token, err := googleOauthConfig.Exchange(context.Background(), code)
if err != nil {
 fmt.Fprintf(w, "Err: %+v", err)
}

fprintf的输出为:

Err: oauth2: cannot fetch token: 401 Unauthorized
Response: {"error":"code_already_used","error_description":"code_already_used"}

我想检查"错误" =" code_aldready_used"。对于我的一生,我无法弄清楚如何。

如何检查/返回/读取"错误"或err的" error_description"?

我已经查看了oauth2代码,它在我上方有点。

// retrieveToken takes a *Config and uses that to retrieve an *internal.Token.
// This token is then mapped from *internal.Token into an *oauth2.Token which is returned along
// with an error..
func retrieveToken(ctx context.Context, c *Config, v url.Values) (*Token, error) {
    tk, err := internal.RetrieveToken(ctx, c.ClientID, c.ClientSecret, c.Endpoint.TokenURL, v)
    if err != nil {
        if rErr, ok := err.(*internal.RetrieveError); ok {
            return nil, (*RetrieveError)(rErr)
        }
        return nil, err
    }
    return tokenFromInternal(tk), nil
}

我如何猜测我试图看到(*检索)部分。对吗?

谢谢!

表达式:

(*RetrieveError)(rErr)

rErr的类型从*internal.RetrieveError转换为*RetrieveError。并且由于RetrieveErroroauth2软件包中声明,因此您可以 type ostert 您收到的*oauth2.RetrieveError的错误以获取详细信息。细节包含在该类型的身体字段中,作为字节片。

由于一块字节不是要检查的最佳格式,在您的情况下,字节似乎包含一个JSON对象,您可以通过预先定义可以删除这些细节的类型来使您的生活更轻松。

是:

type ErrorDetails struct {
    Error            string `json:"error"`
    ErrorDescription string `json:"error_description"`
}
token, err := googleOauthConfig.Exchange(context.Background(), code)
if err != nil {
    fmt.Fprintf(w, "Err: %+v", err)
    if rErr, ok := err.(*oauth2.RetrieveError); ok {
        details := new(ErrorDetails)
        if err := json.Unmarshal(rErr.Body, details); err != nil {
            panic(err)
        }
        fmt.Println(details.Error, details.ErrorDescription)
    }        
}

可以这样做。


arr := strings.Split(err.Error(), "n")
        str := strings.Replace(arr[1], "Response: ", "", 1)
        var details ErrorDetails
        var json = jsoniter.ConfigCompatibleWithStandardLibrary
        err := json.Unmarshal([]byte(str), &details)
        if err == nil {
            beego.Debug(details.Error)
            beego.Debug(details.ErrorDescription)
        }

最新更新