如何正确读取golang oauth2中的错误

如何正确读取golang oauth2中的错误,go,oauth,oauth-2.0,godoc,Go,Oauth,Oauth 2.0,Godoc,fprintf的输出为: token, err := googleOauthConfig.Exchange(context.Background(), code) if err != nil { fmt.Fprintf(w, "Err: %+v", err) } 我想检查“error”=“code\u已使用”。就我个人而言,我不知道该怎么做 如何检查/返回/读取错误的“错误”或“错误描述”? 我看过oauth2代码,它比我略高 Err: oauth2: cannot fetch token:

fprintf的输出为:

token, err := googleOauthConfig.Exchange(context.Background(), code)
if err != nil {
 fmt.Fprintf(w, "Err: %+v", err)
}
我想检查“error”=“code\u已使用”。就我个人而言,我不知道该怎么做

如何检查/返回/读取错误的“错误”或“错误描述”?

我看过oauth2代码,它比我略高

Err: oauth2: cannot fetch token: 401 Unauthorized
Response: {"error":"code_already_used","error_description":"code_already_used"}
我想我是想看看(*RetrieveError)部分。对吧?

谢谢大家!

表达式:

// 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
}
rErr
的类型从
*internal.RetrieveError
转换为
*RetrieveError
。由于
oauth2
包中声明了
RetrieveError
,因此可以键入assert以获取详细信息。详细信息以字节片的形式包含在该类型的Body字段中

由于字节片不是要检查的最佳格式,而且在您的情况下,字节似乎包含一个json对象,因此您可以通过预定义一个类型(您可以将这些细节解组到该类型中)来简化您的工作

即:

(*RetrieveError)(rErr)
我可以这样做

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)
        }