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

报告相同问题?

悬赏问题

  • ¥15 java 操作 elasticsearch 8.1 实现 索引的重建
  • ¥15 数据可视化Python
  • ¥15 要给毕业设计添加扫码登录的功能!!有偿
  • ¥15 kafka 分区副本增加会导致消息丢失或者不可用吗?
  • ¥15 微信公众号自制会员卡没有收款渠道啊
  • ¥15 stable diffusion
  • ¥100 Jenkins自动化部署—悬赏100元
  • ¥15 关于#python#的问题:求帮写python代码
  • ¥20 MATLAB画图图形出现上下震荡的线条
  • ¥15 关于#windows#的问题:怎么用WIN 11系统的电脑 克隆WIN NT3.51-4.0系统的硬盘