Skip to content

Commit c315710

Browse files
committed
refactor raise error to lower perceived complexity
1 parent dc39b4e commit c315710

File tree

1 file changed

+20
-6
lines changed

1 file changed

+20
-6
lines changed

lib/slack/web/faraday/response/raise_error.rb

Lines changed: 20 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -4,19 +4,33 @@ module Web
44
module Faraday
55
module Response
66
class RaiseError < ::Faraday::Middleware
7-
def on_complete(env)
7+
def throw_if_too_many_requests(env)
88
raise Slack::Web::Api::Errors::TooManyRequestsError, env.response if env.status == 429
9+
end
10+
11+
def throw_if_response_is_invalid_json(env)
12+
return unless !response_content_type_is_a_string?(env) && !env.body.is_a?(Hash)
13+
14+
raise ::Faraday::ParsingError.new(nil, env.response)
15+
end
916

10-
response_content_type_is_string = env.response&.headers&.[]('content-type')&.include?('text/plain') || false
17+
def response_content_type_is_a_string?(env)
18+
env.response&.headers&.[]('content-type')&.include?('text/plain') || false
19+
end
1120

12-
raise ::Faraday::ParsingError.new(nil, env.response) if !response_content_type_is_string && !env.body.is_a?(Hash)
21+
def should_return?(env)
22+
body = env.body
23+
(env.success? && body.is_a?(String) && response_content_type_is_a_string?(env)) || !body || body['ok']
24+
end
25+
26+
def on_complete(env)
27+
throw_if_too_many_requests(env)
28+
throw_if_response_is_invalid_json(env)
1329

1430
return unless env.success?
1531

1632
body = env.body
17-
return if env.success? && body.is_a?(String) && response_content_type_is_string
18-
return unless body
19-
return if body['ok']
33+
return if should_return?(env)
2034

2135
error_message = body['error'] || body['errors'].map { |message| message['error'] }.join(',')
2236
error_class = Slack::Web::Api::Errors::ERROR_CLASSES[error_message]

0 commit comments

Comments
 (0)