lib/unsplash/connection.rb in unsplash-1.5.6 vs lib/unsplash/connection.rb in unsplash-2.0.0
- old
+ new
@@ -60,13 +60,12 @@
# Create and assign new access token from extracted token. To be used with
# extract_token to reauthorize app without api call.
# @param token_extract [Hash] OAuth token hash from #extract_token.
# @return [OAuth2::AccessToken, nil] New access token object.
def create_and_assign_token(token_extract)
- unless token_extract.nil?
- @oauth_token = OAuth2::AccessToken.from_hash(@oauth, token_extract)
- end
+ return if !token_extract
+ @oauth_token = OAuth2::AccessToken.from_hash(@oauth, token_extract)
end
# Perform a GET request.
# @param path [String] The path at which to make ther request.
# @param params [Hash] A hash of request parameters.
@@ -110,33 +109,40 @@
headers = {
"Accept-Version" => @api_version
# Anything else? User agent?
}
- response = if @oauth_token
- refresh_token!
+ response = begin
+ if @oauth_token
+ refresh_token!
- param_key = verb == :post ? :body : :params
- @oauth_token.public_send(verb, @api_base_uri + path, param_key => params, headers: headers)
- else
- self.class.public_send verb, path, query: params, headers: public_auth_header
+ param_key = verb == :post ? :body : :params
+ @oauth_token.public_send(verb, @api_base_uri + path, param_key => params, headers: headers)
+ else
+ self.class.public_send verb, path, query: params, headers: public_auth_header
+ end
+ rescue OAuth2::Error => e
+ OpenStruct.new(headers: {}, status: 403, body: e.error_message(e.response.body))
end
if response.headers["Warning"]
Unsplash.configuration.logger.warn response.headers["Warning"]
end
status_code = response.respond_to?(:status) ? response.status : response.code
- begin
- if !(200..299).include?(status_code)
- body = JSON.parse(response.body)
- msg = body["error"] || body["errors"].join(" ")
- raise Unsplash::Error.new msg
- end
- rescue JSON::ParserError
- raise Unsplash::Error.new response.body
+ case status_code
+ when 200..299
+ response
+ when 401
+ raise Unsplash::UnauthorizedError.new(error_message(response))
+ when 403
+ raise Unsplash::ForbiddenError.new(error_message(response))
+ when 404
+ raise Unsplash::NotFoundError.new(error_message(response))
+ else
+ raise Unsplash::Error.new(error_message(response))
end
response
end
@@ -154,8 +160,15 @@
def refresh_token!
return if !@oauth_token.expired?
@oauth_token = @oauth_token.refresh_token
+ end
+
+ def error_message(response)
+ body = JSON.parse(response.body)
+ body["error"] || body["errors"].join(" ")
+ rescue JSON::ParserError
+ raise Unsplash::Error.new(response.body)
end
end
end