When I write ruby or (rails), where should I write begin
and rescue
about http request (or just in general, where to write begin rescue)?
I'm talking about controller, model or module.
For example, I wrote codes like this.
module
module WhateverModule
def get_list
http, uri_path, headers = set_request("whatever_api_url")
http.get(uri_path, headers)
end
#codes continue below
end
then, I often time puts begin
and rescue
code at controller.
controller
begin
api_list = get_list
rescue => exception
# do whatever I need to do to handle exceptions
p "exception happened!"
end
but my PR reviewer keep saying "you should write a code like this"
module
module WhateverModule
def get_list
http, uri_path, headers = set_request("whatever_api_url")
begin
http.get(uri_path, headers)
rescue => exception
p "exception happend!"
end
end
#codes continue below
end
My question is, which one is right (or clean or better)?
Are there any general consensuses about where to put begin
and rescue
?
Thanks
CodePudding user response:
I would argue that when using rescue
blocks it is a common pattern to follow two guidelines:
- Put the
rescue
block only around the lowest number of lines possible. Usually, this should only be one line. That certainly depends on your code but in general, exceptions are raised by specific methods. Therescue
block should only be around that block if possible. That makes debugging and refactoring much easier. - When adding a
rescue
block then name those exceptions that you expect to happen precisely. Otherwise you might catch errors that you didn't expect (syntax errors or method calls onnil
). What again makes debugging much harder.
In your example, I agree with the PR reviewer but I would add the specific exceptions that might occur and that I want to handle. for example like this:
def get_list
http, uri_path, headers = set_request("whatever_api_url")
begin
http.get(uri_path, headers)
rescue Net::HTTPNotFound => e
# handle page not found
rescue Net::HTTPForbidden => e
# handle invalid credentials
rescue Net::HTTPServerError, Net::HTTPServerException
# handle server error
end
end
Of cause, how to handle exceptions and if that is even possible depends on your application. And therefore there is no hard rule but only there guidelines.