Skip to content
This repository was archived by the owner on Jul 19, 2025. It is now read-only.

Commit f4ce2aa

Browse files
committed
Merge pull request #23 from codeclimate/pb-response-check
Replace Faraday Middleware with something custom
2 parents 664cd03 + 88e8a41 commit f4ce2aa

File tree

3 files changed

+48
-2
lines changed

3 files changed

+48
-2
lines changed

lib/cc/service/http.rb

Lines changed: 3 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,5 @@
1-
require 'active_support/concern'
1+
require "active_support/concern"
2+
require "cc/service/response_check"
23

34
module CC::Service::HTTP
45
extend ActiveSupport::Concern
@@ -52,8 +53,8 @@ def http(options = {})
5253
options[:ssl][:ca_file] ||= ca_file
5354

5455
Faraday.new(options) do |b|
56+
b.use(CC::Service::ResponseCheck)
5557
b.request(:url_encoded)
56-
b.response(:raise_error)
5758
b.adapter(*Array(options[:adapter] || config[:adapter]))
5859
end
5960
end

lib/cc/service/invocation/with_error_handling.rb

Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -22,9 +22,16 @@ def call
2222
private
2323

2424
def error_message(ex)
25+
if ex.respond_to?(:response_body)
26+
response_body = ". Response: <#{ex.response_body.inspect}>"
27+
else
28+
response_body = ""
29+
end
30+
2531
message = "Exception invoking service:"
2632
message << " [#{@prefix}]" if @prefix
2733
message << " (#{ex.class}) #{ex.message}"
34+
message << response_body
2835
end
2936
end
3037
end

lib/cc/service/response_check.rb

Lines changed: 38 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,38 @@
1+
class CC::Service
2+
class HTTPError < StandardError
3+
attr_reader :response_body
4+
5+
def initialize(message, response_body)
6+
@response_body = response_body
7+
8+
super(message)
9+
end
10+
end
11+
12+
class ResponseCheck < Faraday::Response::Middleware
13+
ErrorStatuses = 400...600
14+
15+
def on_complete(env)
16+
if ErrorStatuses === env[:status]
17+
message = error_message(env) ||
18+
"API request unsuccessful (#{env[:status]})"
19+
20+
raise HTTPError.new(message, env[:body])
21+
end
22+
end
23+
24+
private
25+
26+
def error_message(env)
27+
# We only handle Jira (or responses which look like Jira's). We will add
28+
# more logic here over time to account for other service's typical error
29+
# responses as we see them.
30+
if env[:response_headers]["content-type"] =~ /application\/json/
31+
errors = JSON.parse(env[:body])["errors"]
32+
errors.is_a?(Hash) && errors.values.map(&:capitalize).join(", ")
33+
end
34+
rescue JSON::ParserError
35+
end
36+
37+
end
38+
end

0 commit comments

Comments
 (0)