2 回答

TA貢獻1860條經驗 獲得超8個贊
可以這樣做。
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)
}

TA貢獻1775條經驗 獲得超11個贊
表達方式:
(*RetrieveError)(rErr)
rErr將的類型從轉換*internal.RetrieveError為*RetrieveError。由于RetrieveError是在oauth2包中聲明的,您可以鍵入斷言您收到的錯誤*oauth2.RetrieveError以獲取詳細信息。詳細信息作為字節片段包含在該類型的 Body 字段中。
由于一片字節不是要檢查的最佳格式,并且在您的情況下,字節似乎包含一個 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)
}
}
- 2 回答
- 0 關注
- 170 瀏覽
添加回答
舉報