Class: Academical::HttpClient::ErrorHandler
- Inherits:
-
Faraday::Middleware
- Object
- Faraday::Middleware
- Academical::HttpClient::ErrorHandler
- Defined in:
- lib/academical/http_client/error_handler.rb
Overview
ErrorHanlder takes care of selecting the error message from response body
Instance Method Summary collapse
- #call(env) ⇒ Object
-
#initialize(app) ⇒ ErrorHandler
constructor
A new instance of ErrorHandler.
Constructor Details
#initialize(app) ⇒ ErrorHandler
Returns a new instance of ErrorHandler.
8 9 10 |
# File 'lib/academical/http_client/error_handler.rb', line 8 def initialize(app) super(app) end |
Instance Method Details
#call(env) ⇒ Object
12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 |
# File 'lib/academical/http_client/error_handler.rb', line 12 def call(env) @app.call(env).on_complete do |env| code = env[:response].status type = env[:response].headers["content-type"] case code when 500...599 raise Academical::Error::ClientError.new("Error #{code}", code) when 400...499 body = Academical::HttpClient::ResponseHandler.get_body(env[:response]) = "" # If HTML, whole body is taken if body.is_a?(String) = body end # If JSON, a particular field is taken and used if type.include?("json") and body.is_a?(Hash) if body.has_key?("message") = body["message"] else = "Unable to select error message from json returned by request responsible for error" end end if == "" = "Unable to understand the content type of response returned by request responsible for error" end raise Academical::Error::ClientError.new , code end end end |