duanli9569 2019-03-05 19:31 采纳率: 100%
浏览 164
已采纳

如何从Golang OAuth2中正确读取错误

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

The output of the fprintf is:

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

I want to check if "error" = "code_already_used". For the life of me, I can't sort out how.

How do I check/return/read "error" or "error_description" of err?

I've looked at the oauth2 code and it's a bit above me.

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

How guess I'm trying to see the (*RetrieveError) part. Right?

THANK YOU!

  • 写回答

2条回答 默认 最新

  • duanhan4763 2019-03-05 19:54
    关注

    The expression:

    (*RetrieveError)(rErr)
    

    converts therErr's type from *internal.RetrieveError to *RetrieveError. And since RetrieveError is declared in the oauth2 package, you can type assert the error you receive to *oauth2.RetrieveError to get the details. The details are contained in that type's Body field as a slice of bytes.

    Since a slice of bytes is not the best format to be inspected and in your case it seems like the bytes contain a json object you can make your life easier by predefining a type into which you can unmarshal those details.

    That is:

    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)
        }        
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥60 版本过低apk如何修改可以兼容新的安卓系统
  • ¥25 由IPR导致的DRIVER_POWER_STATE_FAILURE蓝屏
  • ¥50 有数据,怎么建立模型求影响全要素生产率的因素
  • ¥50 有数据,怎么用matlab求全要素生产率
  • ¥15 TI的insta-spin例程
  • ¥15 完成下列问题完成下列问题
  • ¥15 C#算法问题, 不知道怎么处理这个数据的转换
  • ¥15 YoloV5 第三方库的版本对照问题
  • ¥15 请完成下列相关问题!
  • ¥15 drone 推送镜像时候 purge: true 推送完毕后没有删除对应的镜像,手动拷贝到服务器执行结果正确在样才能让指令自动执行成功删除对应镜像,如何解决?