You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

49 lines
1.2 KiB

  1. package cos
  2. import (
  3. "encoding/xml"
  4. "fmt"
  5. "io/ioutil"
  6. "net/http"
  7. )
  8. // ErrorResponse 包含 API 返回的错误信息
  9. //
  10. // https://www.qcloud.com/document/product/436/7730
  11. type ErrorResponse struct {
  12. XMLName xml.Name `xml:"Error"`
  13. Response *http.Response `xml:"-"`
  14. Code string
  15. Message string
  16. Resource string
  17. RequestID string `header:"x-cos-request-id,omitempty" url:"-" xml:"-"`
  18. TraceID string `xml:"TraceId,omitempty"`
  19. }
  20. // Error returns the error msg
  21. func (r *ErrorResponse) Error() string {
  22. RequestID := r.RequestID
  23. if RequestID == "" {
  24. RequestID = r.Response.Header["X-Cos-Request-Id"][0]
  25. }
  26. TraceID := r.TraceID
  27. if TraceID == "" {
  28. TraceID = r.Response.Header["X-Cos-Trace-Id"][0]
  29. }
  30. return fmt.Sprintf("%v %v: %d %v(Message: %v, RequestId: %v, TraceId: %v)",
  31. r.Response.Request.Method, r.Response.Request.URL,
  32. r.Response.StatusCode, r.Code, r.Message, RequestID, TraceID)
  33. }
  34. // 检查 response 是否是出错时的返回的 response
  35. func checkResponse(r *http.Response) error {
  36. if c := r.StatusCode; 200 <= c && c <= 299 {
  37. return nil
  38. }
  39. errorResponse := &ErrorResponse{Response: r}
  40. data, err := ioutil.ReadAll(r.Body)
  41. if err == nil && data != nil {
  42. xml.Unmarshal(data, errorResponse)
  43. }
  44. return errorResponse
  45. }