-
Notifications
You must be signed in to change notification settings - Fork 27
/
chatwork_error.rb
82 lines (65 loc) · 2.16 KB
/
chatwork_error.rb
1
2
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
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
module ChatWork
class ChatWorkError < StandardError
def self.from_response(status, body, headers)
body ||= {}
if headers.has_key?("WWW-Authenticate")
return AuthenticateError.from_www_authenticate(
www_authenticate: headers["WWW-Authenticate"],
status: status,
error_response: body["errors"],
)
end
return APIError.new(status, body["errors"]) if body["errors"]
if body["error"]
message = [body["error"], body["error_description"]].compact.join(" ")
return AuthenticateError.new(message, status, body, body["error"], body["error_description"])
end
APIConnectionError.new("Invalid response #{body.to_hash} (status: #{status})")
end
attr_reader :status
attr_reader :error_response
def initialize(message, status = nil, error_response = nil)
@status = status
@error_response = error_response
super(message)
end
end
class APIConnectionError < ChatWorkError
def self.faraday_error(e)
new("Connection with ChatWork API server failed. #{e.message}", e)
end
attr_reader :original_error
def initialize(message, original_error = nil)
@original_error = original_error
super(message)
end
end
class APIError < ChatWorkError
attr_reader :errors
def initialize(status, error_response)
@errors = error_response
super(error_response[0], status, error_response)
end
end
class AuthenticateError < ChatWorkError
attr_reader :error, :error_description
def initialize(message, status, error_response, error, error_description)
@error = error
@error_description = error_description
super(message, status, error_response)
end
def self.from_www_authenticate(www_authenticate:, status:, error_response:)
www_authenticate =~ /error="([^\"]+)"/
error = Regexp.last_match(1)
www_authenticate =~ /error_description="([^\"]+)"/
error_description = Regexp.last_match(1)
AuthenticateError.new(
www_authenticate,
status,
error_response,
error,
error_description,
)
end
end
end