unmarshal_error.go 1.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051
  1. package s3
  2. import (
  3. "encoding/xml"
  4. "fmt"
  5. "io"
  6. "net/http"
  7. "strings"
  8. "github.com/aws/aws-sdk-go/aws"
  9. "github.com/aws/aws-sdk-go/aws/awserr"
  10. "github.com/aws/aws-sdk-go/aws/request"
  11. )
  12. type xmlErrorResponse struct {
  13. XMLName xml.Name `xml:"Error"`
  14. Code string `xml:"Code"`
  15. Message string `xml:"Message"`
  16. }
  17. func unmarshalError(r *request.Request) {
  18. defer r.HTTPResponse.Body.Close()
  19. if r.HTTPResponse.StatusCode == http.StatusMovedPermanently {
  20. r.Error = awserr.New("BucketRegionError",
  21. fmt.Sprintf("incorrect region, the bucket is not in '%s' region", aws.StringValue(r.Service.Config.Region)), nil)
  22. return
  23. }
  24. if r.HTTPResponse.ContentLength == int64(0) {
  25. // No body, use status code to generate an awserr.Error
  26. r.Error = awserr.NewRequestFailure(
  27. awserr.New(strings.Replace(r.HTTPResponse.Status, " ", "", -1), r.HTTPResponse.Status, nil),
  28. r.HTTPResponse.StatusCode,
  29. "",
  30. )
  31. return
  32. }
  33. resp := &xmlErrorResponse{}
  34. err := xml.NewDecoder(r.HTTPResponse.Body).Decode(resp)
  35. if err != nil && err != io.EOF {
  36. r.Error = awserr.New("SerializationError", "failed to decode S3 XML error response", nil)
  37. } else {
  38. r.Error = awserr.NewRequestFailure(
  39. awserr.New(resp.Code, resp.Message, nil),
  40. r.HTTPResponse.StatusCode,
  41. "",
  42. )
  43. }
  44. }