Answer the question
In order to leave comments, you need to log in
More correct way to handle not found entity?
Hello!
Is there any significant difference in the two approaches for handling an entity not found?
Suppose the only thing to do if the entity is not found is to go to the main page
Method 1:
entity = Entity.find(params[:id]) rescue redirect_to('/')
entity = Entity.find_by_id(params[:id])
redirect_to('/') unless entity
Answer the question
In order to leave comments, you need to log in
There should always be a find. And the error is caught in the ApplicationController
unless Rails.application.config.consider_all_requests_local
rescue_from Exception, with: :respond_with_500
rescue_from ActiveRecord::RecordNotFound,
ActionController::RoutingError,
ActiveRecord::RecordInvalid,
with: :respond_with_404
rescue_from ActionController::BadRequest, with: :respond_with_400
end
def respond_with_404(exception=nil)
redirect_to root_path
end
Suppose the only thing to do if the entity is not found is to go to the main pageWrong. It is necessary to give an error message that the entity was not found. with an error code.
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question