From ceea1293b3e18de398a3cb07f6b61df24f3d48c8 Mon Sep 17 00:00:00 2001 From: Cory Lown Date: Tue, 3 Dec 2024 13:53:44 -0500 Subject: [PATCH] Handle non-successful response from borrowdirect --- app/models/borrow_direct_reshare_requests.rb | 3 +++ app/services/borrow_direct_reshare_client.rb | 14 +++++++++++--- 2 files changed, 14 insertions(+), 3 deletions(-) diff --git a/app/models/borrow_direct_reshare_requests.rb b/app/models/borrow_direct_reshare_requests.rb index 91994f0f..5172cf7b 100644 --- a/app/models/borrow_direct_reshare_requests.rb +++ b/app/models/borrow_direct_reshare_requests.rb @@ -23,6 +23,9 @@ def reshare_requests request_client.requests(patron_university_id).map do |request| ReshareRequest.new(request) end + rescue BorrowDirectReshareClient::BorrowDirectError => e + Honeybadger.notify(e) + [] end def request_client diff --git a/app/services/borrow_direct_reshare_client.rb b/app/services/borrow_direct_reshare_client.rb index 241a9ecc..96b6d829 100644 --- a/app/services/borrow_direct_reshare_client.rb +++ b/app/services/borrow_direct_reshare_client.rb @@ -3,6 +3,8 @@ require 'http' class BorrowDirectReshareClient + class BorrowDirectError < StandardError; end + DEFAULT_HEADERS = { accept: 'application/json, text/plain', content_type: 'application/json' @@ -25,7 +27,7 @@ def get(path, **) end def get_json(path, **) - parse(get(path, **)) + parse(check_response(get(path, **))) end def requests(university_id) @@ -45,8 +47,14 @@ def ping private + def check_response(response) + return response if [200, 201].include?(response.status) + + raise BorrowDirectError, "Response status: #{response.status}; Response body: #{response.body}" + end + def parse(response) - return nil if !response || response.body.empty? + return nil unless response.respond_to?(:body) && !response.body.empty? JSON.parse(response.body) rescue JSON::ParserError => e @@ -56,7 +64,7 @@ def parse(response) def session_token @session_token ||= begin response = request('/authn/login', json: { username: @username, password: @password }, method: :post) - response ? response['x-okapi-token'] : nil + check_response(response) ? response['x-okapi-token'] : nil end end