Commit a3a98039 authored by Peter Leitzen's avatar Peter Leitzen

Extract parsing JSON

parent 9817124f
...@@ -85,8 +85,6 @@ module Gitlab ...@@ -85,8 +85,6 @@ module Gitlab
path = api_path(type) path = api_path(type)
response = get(path, args) response = get(path, args)
handle_response(response) handle_response(response)
rescue JSON::ParserError
raise PrometheusClient::Error, 'Parsing response failed'
rescue RestClient::ExceptionWithResponse => ex rescue RestClient::ExceptionWithResponse => ex
if ex.response if ex.response
handle_exception_response(ex.response) handle_exception_response(ex.response)
...@@ -109,7 +107,7 @@ module Gitlab ...@@ -109,7 +107,7 @@ module Gitlab
end end
def handle_response(response) def handle_response(response)
json_data = JSON.parse(response.body) json_data = parse_json(response.body)
if response.code == 200 && json_data['status'] == 'success' if response.code == 200 && json_data['status'] == 'success'
json_data['data'] || {} json_data['data'] || {}
else else
...@@ -121,18 +119,22 @@ module Gitlab ...@@ -121,18 +119,22 @@ module Gitlab
if response.code == 200 && response['status'] == 'success' if response.code == 200 && response['status'] == 'success'
response['data'] || {} response['data'] || {}
elsif response.code == 400 elsif response.code == 400
json_data = JSON.parse(response.body) json_data = parse_json(response.body)
raise PrometheusClient::QueryError, json_data['error'] || 'Bad data received' raise PrometheusClient::QueryError, json_data['error'] || 'Bad data received'
else else
raise PrometheusClient::Error, "#{response.code} - #{response.body}" raise PrometheusClient::Error, "#{response.code} - #{response.body}"
end end
rescue JSON::ParserError
raise PrometheusClient::Error, 'Parsing response failed'
end end
def get_result(expected_type) def get_result(expected_type)
data = yield data = yield
data['result'] if data['resultType'] == expected_type data['result'] if data['resultType'] == expected_type
end end
def parse_json(response_body)
JSON.parse(response_body)
rescue JSON::ParserError
raise PrometheusClient::Error, 'Parsing response failed'
end
end end
end end
Markdown is supported
0%
or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment