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.

75 lines
1.7 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:"RequestId,omitempty"`
  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.Get("X-Cos-Request-Id")
  25. }
  26. TraceID := r.TraceID
  27. if TraceID == "" {
  28. TraceID = r.Response.Header.Get("X-Cos-Trace-Id")
  29. }
  30. decodeURL, err := decodeURIComponent(r.Response.Request.URL.String())
  31. if err != nil {
  32. decodeURL = r.Response.Request.URL.String()
  33. }
  34. return fmt.Sprintf("%v %v: %d %v(Message: %v, RequestId: %v, TraceId: %v)",
  35. r.Response.Request.Method, decodeURL,
  36. r.Response.StatusCode, r.Code, r.Message, RequestID, TraceID)
  37. }
  38. // 检查 response 是否是出错时的返回的 response
  39. func checkResponse(r *http.Response) error {
  40. if c := r.StatusCode; 200 <= c && c <= 299 {
  41. return nil
  42. }
  43. errorResponse := &ErrorResponse{Response: r}
  44. data, err := ioutil.ReadAll(r.Body)
  45. if err == nil && data != nil {
  46. xml.Unmarshal(data, errorResponse)
  47. }
  48. return errorResponse
  49. }
  50. func IsNotFoundError(e error) bool {
  51. if e == nil {
  52. return false
  53. }
  54. err, ok := e.(*ErrorResponse)
  55. if !ok {
  56. return false
  57. }
  58. if err.Response != nil && err.Response.StatusCode == 404 {
  59. return true
  60. }
  61. return false
  62. }
  63. func IsCOSError(e error) (*ErrorResponse, bool) {
  64. if e == nil {
  65. return nil, false
  66. }
  67. err, ok := e.(*ErrorResponse)
  68. return err, ok
  69. }