When you are calling a method that may raise an exception that you don't care about, you might think of doing something like this:
@user = User.power_find(something) rescue User.new
Do not do that! You will be rescuing away StandardError
and all its subclasses, like NameError
-- meaning that even a typo in your code won't raise an error.
Instead, rescue the exception type that you are expecting:
@user = begin
User.power_find(something)
rescue ActiveRecord::RecordNotFound
User.new
end
This also applies to the quite popular "rescue nil
" and "full" rescue
blocks that don't explicitly rescue away an error class:
begin
# do stuff
rescue
# rescues any StandardError
end
Note that there may be cases where you want to rescue
all errors. Only use that if you know the impact it has on your application and are absolutely fine with it.
Posted by Arne Hartherz to makandra dev (2012-02-29 13:36)