Class: Moysklad::Client::Errors

Inherits:
Object
  • Object
show all
Defined in:
lib/moysklad/client/errors.rb

Class Method Summary collapse

Class Method Details

.build(res) ⇒ Object



3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
# File 'lib/moysklad/client/errors.rb', line 3

def self.build res
  body = res.body.force_encoding('utf-8')
  content_type = res.headers['content-type']

  if content_type.start_with? 'application/json'
    # ok
  elsif content_type.start_with? 'text/html'
    raise HtmlParsedError, body
  else
    raise UnknownError, body
  end

  # Encoding::UndefinedConversionError
  # "\xD0" from ASCII-8BIT to UTF-8
  begin
    body = JSON.parse body
    Moysklad.logger.debug "Moysklad::Client: #{res.status}: #{res.headers}, #{res.env.url.to_s}\n#{body}"
  rescue Encoding::UndefinedConversionError => err
    Moysklad.logger.error "#{err}"
  rescue JSON::ParserError => err
    Moysklad.logger.error "#{err}: #{res.headers}, body:#{body}"
    raise ParsingError, body
  end

  case res.status
  when 401
    raise UnauthorizedError.new body
  when 403
    raise ResourceForbidden.new body
  when 404
    raise NoResourceFound.new body
  when 405, 412
    raise MethodNotAllowedError.new body
  when 500
    raise InternalServerError.new body
  when 502
    raise BadGatewayError.new body
  else
    raise JsonParsedError.new body
  end
end