31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
|
# File 'lib/optimize_player/client.rb', line 31
def send_request(url, method, params = {})
= {:accept => :json}
url = @api_endpoint + url + "?access_token=#{@access_token}"
case method.to_s.downcase.to_sym
when :get, :delete
url += "#{URI.parse(url).query ? '&' : '?'}#{uri_encode(params)}" if params && params.any?
payload = nil
else
payload = params
end
url = OptimizePlayer::Signer.new.sign_url(url, @secret_key)
request_opts = {
:headers => .update(),
:method => method,
:open_timeout => 30,
:payload => payload,
:url => url,
:timeout => 80
}
begin
response = RestClient::Request.execute(request_opts)
rescue RestClient::BadRequest,
RestClient::Unauthorized,
RestClient::ResourceNotFound,
RestClient::Forbidden,
RestClient::UnprocessableEntity => e
json_obj = JSON.parse(e.http_body)
error = json_obj['error']
message = json_obj['message']
error_klass_name = e.class.name.split('::')[-1]
error_klass = Object.const_get("OptimizePlayer::Errors::#{error_klass_name}")
raise error_klass.new(e.http_code, error, message)
rescue RestClient::MethodNotAllowed => e
raise OptimizePlayer::Errors::MethodNotAllowed.new(405, 'MethodNotAllowed', 'Method Not Allowed')
rescue SocketError => e
message = "Unexpected error communicating when trying to connect to OptimizePlayer. " +
"You may be seeing this message because your DNS is not working."
raise OptimizePlayer::Errors::SocketError.new(nil, 'NetworkError', message)
rescue Errno::ECONNREFUSED => e
message = "Unexpected error communicating with OptimizePlayer."
raise OptimizePlayer::Errors::ConnectionError.new(nil, 'ConnectionError', message)
rescue RestClient::ServerBrokeConnection, RestClient::RequestTimeout => e
message = "Could not connect to OptimizePlayer. " +
"Please check your internet connection and try again."
raise OptimizePlayer::Errors::ConnectionError.new(nil, 'ConnectionError', message)
rescue RestClient::ExceptionWithResponse => e
if code = e.http_code and body = e.http_body
begin
json_obj = JSON.parse(body)
rescue JSON::ParserError
raise_api_error(code, body)
end
error = json_obj['error'] || 'error'
message = json_obj['message'] || 'Unexpected error'
raise OptimizePlayer::Errors::ApiError.new(code, error, message)
else
message = "Unexpected error communicating with OptimizePlayer."
raise OptimizePlayer::Errors::UnhandledError.new(nil, 'UnhandledError', message)
end
end
begin
JSON.parse(response.body)
rescue JSON::ParserError => e
raise_api_error(response.code, response.body)
end
end
|