-
Notifications
You must be signed in to change notification settings - Fork 8
Description
Currently, we don't have any retry logic present if API request fails with some network related exceptions in this line,
response = http.request(request)
we are using Net::HTTP library to make API request and recently it has been seen many request getting end of file reached exception which may be due to this issue.
If we have some retry logic around Client#send_request then it will help to handle these exceptions till some extent.
To add retry logic, we need to define a maximum number of retries, and then wrap the HTTP request in a loop that attempts to resend the request until either it succeeds or it hits the maximum number of retries. We may also want to add a sleep call between retries to prevent quickly exhausting your retry limit in the case of temporary network issues or server-side problems.
module Trolley
class Client
#...
MAX_RETRIES = 3 # Maximum number of retries
#...
private
def send_request(endPoint, method, body = '')
# your original send_request logic here
uri = URI.parse(@config.api_base + endPoint)
#...
begin
retries = 0
response = http.request(request)
rescue StandardError => e
if retries < MAX_RETRIES
retries += 1
sleep(2**retries) # Exponential back-off
retry
else
raise "Request failed after #{MAX_RETRIES} attempts: #{e.message}"
end
end
if response.code != '200' && response.code != '204'
throw_status_code_exception(response.message + ' ' + response.body , response.code)
end
response.body
end
#...
end
endPlease note that:
- The
MAX_RETRIESconstant is defined to specify the maximum number of retry attempts. - I've added a
begin/rescueblock to catch errors that occur during the request. - Inside the
rescueblock, we check if we've hit our maximum number of retries. If not, we increment the retry count, wait for a period of time (sleep(2**retries)provides an exponential back-off), and then retry the request. If we have hit our maximum number of retries, we raise an exception to alert the user that the request has ultimately failed. - We can adjust the
MAX_RETRIESandsleepvalues to suit your specific needs.