I'm trying to implement error handling for my API client. Everything looks pretty good but except of the error I want to error description from the API either (it's inside response.body['FirebirdApiError']['ApiStatusDescription']
). Like below:
# error handler class
module Errors
class APIExceptionError < StandardError; end
BadRequestError = Class.new(APIExceptionError)
UnauthorizedError = Class.new(APIExceptionError)
ForbiddenError = Class.new(APIExceptionError)
ApiRequestsQuotaReachedError = Class.new(APIExceptionError)
NotFoundError = Class.new(APIExceptionError)
UnprocessableEntityError = Class.new(APIExceptionError)
ApiError = Class.new(APIExceptionError)
def error_class(status)
case status
when 400
BadRequestError
when 401
UnauthorizedError
when 403
ForbiddenError
when 404
NotFoundError
when 429
UnprocessableEntityError
else
ApiError
end
end
end
Which is user inside of client class:
#client class
class Client
include ::Errors
def get(path, options = {})
handle_response(client.public_send(:get, path.to_s, options))
end
private
(...)
def handle_response(response)
return response_body(response) if response.success?
raise error_class(response.status)
end
def response_body(response)
return if response.body.blank?
response.body
end
end
Which works well but when I'll reach 400 error it will show me Errors::BadRequestError
. I don't think it's handy in case where the API provides a pretty good description of the cause of the error inside response.body['FirebirdApiError']['ApiStatusDescription']
. How do I add this message to display with the error?
CodePudding user response:
You want to add error message when your raise error, right? Maybe you can try
raise error_class(response.status).new(response.body['FirebirdApiError']['ApiStatusDescription'])