Exception: Gitlab::Error::ResponseError

Inherits:
Error
  • Object
show all
Defined in:
lib/gitlab/error.rb

Constant Summary collapse

POSSIBLE_MESSAGE_KEYS =
%i[message error_description error].freeze

Instance Method Summary collapse

Constructor Details

#initialize(response) ⇒ ResponseError

Returns a new instance of ResponseError.



14
15
16
17
# File 'lib/gitlab/error.rb', line 14

def initialize(response)
  @response = response
  super(build_error_message)
end

Instance Method Details

#build_error_message ⇒ Object



32
33
34
35
36
37
38
# File 'lib/gitlab/error.rb', line 32

def build_error_message
  parsed = parsed_response
  message = check_error_keys(parsed)
  "Server responded with code #{@response.status}, message: " \
    "#{handle_message(message)}. " \
    "Request URI: #{@response.env.url}"
end

#check_error_keys(resp) ⇒ Object



40
41
42
43
44
45
# File 'lib/gitlab/error.rb', line 40

def check_error_keys(resp)
  return resp unless resp.is_a?(Gitlab::ObjectifiedHash)

  key = POSSIBLE_MESSAGE_KEYS.find { |k| resp.respond_to?(k) }
  key ? resp.send(key) : resp
end

#error_code ⇒ Object



28
29
30
# File 'lib/gitlab/error.rb', line 28

def error_code
  ''
end

#handle_message(message) ⇒ Object



63
64
65
66
67
68
69
70
71
72
73
74
# File 'lib/gitlab/error.rb', line 63

def handle_message(message)
  case message
  when Gitlab::ObjectifiedHash
    message.to_h.sort.map do |key, val|
      "'#{key}' #{(val.is_a?(Hash) ? val.sort.map { |k, v| "(#{k}: #{v.join(' ')})" } : [val].flatten).join(' ')}"
    end.join(', ')
  when Array
    message.join(' ')
  else
    message
  end
end

#parsed_response ⇒ Object



47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
# File 'lib/gitlab/error.rb', line 47

def parsed_response
  return @parsed_response if defined?(@parsed_response)

  body = @response.body
  return {} if body.nil? || body.empty?

  parsed = JSON.parse(body)
  @parsed_response = if parsed.is_a?(Hash)
                       Gitlab::ObjectifiedHash.new(parsed)
                     else
                       parsed
                     end
rescue JSON::ParserError
  @parsed_response = @response.body
end

#response_message ⇒ Object



23
24
25
26
# File 'lib/gitlab/error.rb', line 23

def response_message
  parsed = parsed_response
  parsed.respond_to?(:message) ? parsed.message : parsed.to_s
end

#response_status ⇒ Object



19
20
21
# File 'lib/gitlab/error.rb', line 19

def response_status
  @response.status
end