error.go 1.9 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061
  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. RawMessage string // OSS返回的原始消息内容
  16. StatusCode int // HTTP状态码
  17. }
  18. // Implement interface error
  19. func (e ServiceError) Error() string {
  20. return fmt.Sprintf("oss: service returned error: StatusCode=%d, ErrorCode=%s, ErrorMessage=%s, RequestId=%s",
  21. e.StatusCode, e.Code, e.Message, e.RequestID)
  22. }
  23. // UnexpectedStatusCodeError is returned when a storage service responds with neither an error
  24. // nor with an HTTP status code indicating success.
  25. type UnexpectedStatusCodeError struct {
  26. allowed []int // 预期OSS返回HTTP状态码
  27. got int // OSS实际返回HTTP状态码
  28. }
  29. // Implement interface error
  30. func (e UnexpectedStatusCodeError) Error() string {
  31. s := func(i int) string { return fmt.Sprintf("%d %s", i, http.StatusText(i)) }
  32. got := s(e.got)
  33. expected := []string{}
  34. for _, v := range e.allowed {
  35. expected = append(expected, s(v))
  36. }
  37. return fmt.Sprintf("oss: status code from service response is %s; was expecting %s",
  38. got, strings.Join(expected, " or "))
  39. }
  40. // Got is the actual status code returned by oss.
  41. func (e UnexpectedStatusCodeError) Got() int {
  42. return e.got
  43. }
  44. // checkRespCode returns UnexpectedStatusError if the given response code is not
  45. // one of the allowed status codes; otherwise nil.
  46. func checkRespCode(respCode int, allowed []int) error {
  47. for _, v := range allowed {
  48. if respCode == v {
  49. return nil
  50. }
  51. }
  52. return UnexpectedStatusCodeError{allowed, respCode}
  53. }