PageRenderTime 114ms CodeModel.GetById 107ms app.highlight 4ms RepoModel.GetById 0ms 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
 1module Spree
 2  module API
 3    class Client
 4      class Error < StandardError
 5
 6        # Raised when Spree returns a 4xx or 500 HTTP status code
 7        class ClientError < Error
 8
 9          # Creates a new error from an HTTP environement
10          #
11          # @param error [Exception]
12          # @return [Spree::API::Client::Error::ClientError]
13          def initialize(error=nil)
14            if error.respond_to?(:response) && !error.response.nil?
15              http_error = error.response[:status].to_i
16
17              if ERROR_MAP.has_key?(http_error)
18                raise ERROR_MAP[http_error].new(
19                  message: error.response[:body]["error"],
20                  validation_errors: error.response[:body]["errors"] || error.response[:body]["exception"])
21              else
22                super
23              end
24            else
25              super
26            end
27          end
28        end # ClientError
29
30        # Raised when Spree returns a 401 HTTP status code
31        class Unauthorized < Error; end
32
33        # Raised when Spree returns a 404 HTTP status code
34        class NotFound < Error; end
35
36        # Raised when Spree returns a 422 HTTP status code
37        class UnprocessableEntity < Error; end
38
39        ERROR_MAP = {
40          401 => Spree::API::Client::Error::Unauthorized,
41          404 => Spree::API::Client::Error::NotFound,
42          422 => Spree::API::Client::Error::UnprocessableEntity
43        }
44      end # Error
45    end
46  end
47end