lib/xhash/client/json_api.rb in xhash_client-0.3.2 vs lib/xhash/client/json_api.rb in xhash_client-0.3.3
- old
+ new
@@ -11,11 +11,17 @@
def api_get(url:, headers: {})
custom_headers = headers.merge(default_headers)
response = HTTParty.get(Xhash.api_base + url, headers: custom_headers)
- JSON.parse(response.body, symbolize_names: true)
+ raise Xhash::Error.new(response) unless response_ok?(response)
+
+ begin
+ JSON.parse(response.body, symbolize_names: true)
+ rescue => exception
+ raise Xhash::MalformedResponse.new
+ end
end
def api_post(url:, body: {}, headers: {})
custom_headers = headers.merge(default_headers)
@@ -23,11 +29,17 @@
HTTParty.post(
Xhash.api_base + url,
body: body.to_json, headers: custom_headers
)
- JSON.parse(response.body, symbolize_names: true)
+ raise Xhash::Error.new(response) unless response_ok?(response)
+
+ begin
+ JSON.parse(response.body, symbolize_names: true)
+ rescue => exception
+ raise Xhash::MalformedResponse.new
+ end
end
def api_post_multipart(url:, body: {}, headers: {})
custom_headers = headers.merge(default_headers)
@@ -35,10 +47,15 @@
HTTParty.post(
Xhash.api_base + url,
multipart: true, body: body, headers: custom_headers
)
+ raise Xhash::Error.new(response) unless response_ok?(response)
response.body
+ end
+
+ def response_ok?(response)
+ !(response.code == 404 || response.code >= 500)
end
end
def self.included(base)
base.extend(ClassMethods)