error_utils.go 1.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051
  1. package xml
  2. import (
  3. "encoding/xml"
  4. "fmt"
  5. "io"
  6. )
  7. // ErrorComponents represents the error response fields
  8. // that will be deserialized from an xml error response body
  9. type ErrorComponents struct {
  10. Code string
  11. Message string
  12. }
  13. // GetErrorResponseComponents returns the error fields from an xml error response body
  14. func GetErrorResponseComponents(r io.Reader, noErrorWrapping bool) (ErrorComponents, error) {
  15. if noErrorWrapping {
  16. var errResponse noWrappedErrorResponse
  17. if err := xml.NewDecoder(r).Decode(&errResponse); err != nil && err != io.EOF {
  18. return ErrorComponents{}, fmt.Errorf("error while deserializing xml error response: %w", err)
  19. }
  20. return ErrorComponents{
  21. Code: errResponse.Code,
  22. Message: errResponse.Message,
  23. }, nil
  24. }
  25. var errResponse wrappedErrorResponse
  26. if err := xml.NewDecoder(r).Decode(&errResponse); err != nil && err != io.EOF {
  27. return ErrorComponents{}, fmt.Errorf("error while deserializing xml error response: %w", err)
  28. }
  29. return ErrorComponents{
  30. Code: errResponse.Code,
  31. Message: errResponse.Message,
  32. }, nil
  33. }
  34. // noWrappedErrorResponse represents the error response body with
  35. // no internal <Error></Error wrapping
  36. type noWrappedErrorResponse struct {
  37. Code string `xml:"Code"`
  38. Message string `xml:"Message"`
  39. }
  40. // wrappedErrorResponse represents the error response body
  41. // wrapped within <Error>...</Error>
  42. type wrappedErrorResponse struct {
  43. Code string `xml:"Error>Code"`
  44. Message string `xml:"Error>Message"`
  45. }