A
A
Anton Ivanov2015-10-03 21:12:29
Ruby on Rails
Anton Ivanov, 2015-10-03 21:12:29

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('/')

Method 2:
entity = Entity.find_by_id(params[:id])
redirect_to('/') unless entity

Answer the question

In order to leave comments, you need to log in

2 answer(s)
Z
Zaporozhchenko Oleg, 2015-10-03
@Fly3110

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

O
OnYourLips, 2015-10-03
@OnYourLips

Suppose the only thing to do if the entity is not found is to go to the main page
Wrong. 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 question

Ask a Question

731 491 924 answers to any question