error.go 1.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960
  1. package oss
  2. import (
  3. "encoding/xml"
  4. "fmt"
  5. "net/http"
  6. "strings"
  7. )
  8. // ServiceError contains fields of the error response from Oss Service REST API.
  9. type ServiceError struct {
  10. XMLName xml.Name `xml:"Error"`
  11. Code string `xml:"Code"` // OSS返回给用户的错误码
  12. Message string `xml:"Message"` // OSS给出的详细错误信息
  13. RequestID string `xml:"RequestId"` // 用于唯一标识该次请求的UUID
  14. HostID string `xml:"HostId"` // 用于标识访问的OSS集群
  15. StatusCode int // HTTP状态码
  16. }
  17. // Implement interface error
  18. func (e ServiceError) Error() string {
  19. return fmt.Sprintf("oss: service returned error: StatusCode=%d, ErrorCode=%s, ErrorMessage=%s, RequestId=%s",
  20. e.StatusCode, e.Code, e.Message, e.RequestID)
  21. }
  22. // UnexpectedStatusCodeError is returned when a storage service responds with neither an error
  23. // nor with an HTTP status code indicating success.
  24. type UnexpectedStatusCodeError struct {
  25. allowed []int // 预期OSS返回HTTP状态码
  26. got int // OSS实际返回HTTP状态码
  27. }
  28. // Implement interface error
  29. func (e UnexpectedStatusCodeError) Error() string {
  30. s := func(i int) string { return fmt.Sprintf("%d %s", i, http.StatusText(i)) }
  31. got := s(e.got)
  32. expected := []string{}
  33. for _, v := range e.allowed {
  34. expected = append(expected, s(v))
  35. }
  36. return fmt.Sprintf("oss: status code from service response is %s; was expecting %s",
  37. got, strings.Join(expected, " or "))
  38. }
  39. // Got is the actual status code returned by oss.
  40. func (e UnexpectedStatusCodeError) Got() int {
  41. return e.got
  42. }
  43. // checkRespCode returns UnexpectedStatusError if the given response code is not
  44. // one of the allowed status codes; otherwise nil.
  45. func checkRespCode(respCode int, allowed []int) error {
  46. for _, v := range allowed {
  47. if respCode == v {
  48. return nil
  49. }
  50. }
  51. return UnexpectedStatusCodeError{allowed, respCode}
  52. }