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.

71 lines
1.6 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. 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. }
  46. func IsNotFoundError(e error) bool {
  47. if e == nil {
  48. return false
  49. }
  50. err, ok := e.(*ErrorResponse)
  51. if !ok {
  52. return false
  53. }
  54. if err.Response != nil && err.Response.StatusCode == 404 {
  55. return true
  56. }
  57. return false
  58. }
  59. func IsCOSError(e error) (*ErrorResponse, bool) {
  60. if e == nil {
  61. return nil, false
  62. }
  63. err, ok := e.(*ErrorResponse)
  64. return err, ok
  65. }