require 'faraday' require 'evrythng/error/bad_request' require 'evrythng/error/enhance_your_calm' require 'evrythng/error/forbidden' require 'evrythng/error/not_acceptable' require 'evrythng/error/not_found' require 'evrythng/error/unauthorized' module Evrythng module Response class RaiseClientError < Faraday::Response::Middleware def on_complete(env) case env[:status].to_i when 400 raise Evrythng::Error::BadRequest.new(error_body(env[:body]), env[:response_headers]) when 401 raise Evrythng::Error::Unauthorized.new(error_body(env[:body]), env[:response_headers]) when 403 raise Evrythng::Error::Forbidden.new(error_body(env[:body]), env[:response_headers]) when 404 raise Evrythng::Error::NotFound.new(error_body(env[:body]), env[:response_headers]) when 406 raise Evrythng::Error::NotAcceptable.new(error_body(env[:body]), env[:response_headers]) when 420 raise Evrythng::Error::EnhanceYourCalm.new(error_body(env[:body]), env[:response_headers]) end end private def error_body(body) if body.nil? '' elsif body['error'] body['error'] elsif body['errors'] first = Array(body['errors']).first if first.kind_of?(Hash) first['message'].chomp else first.chomp end end end end end end