lib/chatwork/chatwork_error.rb in chatwork-0.6.0 vs lib/chatwork/chatwork_error.rb in chatwork-0.6.1
- old
+ new
@@ -1,17 +1,24 @@
module ChatWork
class ChatWorkError < StandardError
def self.from_response(status, body, headers)
- unless body["errors"]
- return APIConnectionError.new("Invalid response #{body}")
+ if headers.has_key?("WWW-Authenticate")
+ return AuthenticateError.from_www_authenticate(
+ www_authenticate: headers["WWW-Authenticate"],
+ status: status,
+ error_response: body["errors"],
+ )
end
- if headers.has_key?("WWW-Authenticate")
- return AuthenticateError.new(headers["WWW-Authenticate"], status, body["errors"])
+ 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
- APIError.new(status, body["errors"])
+ APIConnectionError.new("Invalid response #{body.to_hash} (status: #{status})")
end
attr_reader :status
attr_reader :error_response
@@ -27,11 +34,11 @@
new("Connection with ChatWork API server failed. #{e.message}", e)
end
attr_reader :original_error
- def initialize(message, original_error)
+ def initialize(message, original_error = nil)
@original_error = original_error
super(message)
end
end
@@ -45,16 +52,29 @@
end
class AuthenticateError < ChatWorkError
attr_reader :error, :error_description
- def initialize(message, status, error_response)
- message =~ /error="([^\"]+)"/
- @error = Regexp.last_match(1)
+ def initialize(message, status, error_response, error, error_description)
+ @error = error
+ @error_description = error_description
- message =~ /error_description="([^\"]+)"/
- @error_description = Regexp.last_match(1)
-
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