PageRenderTime 31ms CodeModel.GetById 30ms RepoModel.GetById 1ms app.codeStats 0ms

/lib/spree-api-client/error.rb

https://github.com/sigurthor/spree-api-client
Ruby | 47 lines | 32 code | 7 blank | 8 comment | 4 complexity | 5b3de252039e1d5d2303e01847930c12 MD5 | raw file
  1. module Spree
  2. module API
  3. class Client
  4. class Error < StandardError
  5. # Raised when Spree returns a 4xx or 500 HTTP status code
  6. class ClientError < Error
  7. # Creates a new error from an HTTP environement
  8. #
  9. # @param error [Exception]
  10. # @return [Spree::API::Client::Error::ClientError]
  11. def initialize(error=nil)
  12. if error.respond_to?(:response) && !error.response.nil?
  13. http_error = error.response[:status].to_i
  14. if ERROR_MAP.has_key?(http_error)
  15. raise ERROR_MAP[http_error].new(
  16. message: error.response[:body]["error"],
  17. validation_errors: error.response[:body]["errors"] || error.response[:body]["exception"])
  18. else
  19. super
  20. end
  21. else
  22. super
  23. end
  24. end
  25. end # ClientError
  26. # Raised when Spree returns a 401 HTTP status code
  27. class Unauthorized < Error; end
  28. # Raised when Spree returns a 404 HTTP status code
  29. class NotFound < Error; end
  30. # Raised when Spree returns a 422 HTTP status code
  31. class UnprocessableEntity < Error; end
  32. ERROR_MAP = {
  33. 401 => Spree::API::Client::Error::Unauthorized,
  34. 404 => Spree::API::Client::Error::NotFound,
  35. 422 => Spree::API::Client::Error::UnprocessableEntity
  36. }
  37. end # Error
  38. end
  39. end
  40. end