-
-
Notifications
You must be signed in to change notification settings - Fork 26
/
error.go
48 lines (44 loc) · 1.21 KB
/
error.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
package cos
import (
"encoding/xml"
"fmt"
"io/ioutil"
"net/http"
)
// ErrorResponse 包含 COS HTTP API 返回的错误信息
//
// https://cloud.tencent.com/document/product/436/7730
type ErrorResponse struct {
XMLName xml.Name `xml:"Error"`
// TODO: use cos.Response instead
Response *http.Response `xml:"-"`
Code string
Message string
Resource string
RequestID string `xml:"RequestId"`
TraceID string `xml:"TraceId,omitempty"`
}
// Error ...
func (r *ErrorResponse) Error() string {
return fmt.Sprintf("%v %v: %d %v(Message: %v, RequestId: %v, TraceId: %v)",
r.Response.Request.Method, r.Response.Request.URL,
r.Response.StatusCode, r.Code, r.Message, r.RequestID, r.TraceID)
}
// 检查 response 是否是出错时的返回的 response
func checkResponse(r *http.Response) error {
if c := r.StatusCode; 200 <= c && c <= 299 {
return nil
}
errorResponse := &ErrorResponse{Response: r}
data, err := ioutil.ReadAll(r.Body)
if err == nil && data != nil {
xml.Unmarshal(data, errorResponse)
}
if errorResponse.RequestID == "" {
errorResponse.RequestID = r.Header.Get(xCosRequestID)
}
if errorResponse.TraceID == "" {
errorResponse.TraceID = r.Header.Get(xCosTraceID)
}
return errorResponse
}