What is the best way to handle the error then ID is not found?
I have this code in my controller:
def show
#match = Match.find(params[:id])
end
I was thinking about something like this:
def show
if #match = Match.find(params[:id])
else
render 'error'
end
end
But I still get:
ActiveRecord::RecordNotFound in MatchesController#show
Couldn't findMatch with 'id'=2
Why?
What is the correct solution?
Rescue it in the base controller and leave your action code as simple as possible.
You don't want to deal not found exception in every action, do you?
class ApplicationController < ActionController::Base
rescue_from ActiveRecord::RecordNotFound, :with => :render_404
def render_404
render :template => "errors/error_404", :status => 404
end
end
By default the find method raises an ActiveRecord::RecordNotFound exception. The correct way of handling a not found record is:
def show
#match = Match.find(params[:id])
rescue ActiveRecord::RecordNotFound => e
render 'error'
end
However, if you prefer an if/else approach, you can use the find_by_id method that will return nil:
def show
#match = Match.find_by_id(params[:id])
if #match.nil? # or unless #match
render 'error'
end
end
You can use find_by_id method it returns nil instead of throwing exception
Model.find_by_id
There is two approaches missing:
One is to use a Null-Object (there I leave research up to you)
Te other one was mentioned, but can be placed more reusable and in a way more elegantly (but it is a bit hidden from you action code because it
works on a somewhat higher level and hides stuff):
class MyScope::MatchController < ApplicationController
before_action :set_match, only: [:show]
def show
# will only render if params[:id] is there and resolves
# to a match that will then be available in #match.
end
private
def set_match
#match = Match.find_by(id: params[:id])
if !#match.present?
# Handle somehow, i.e. with a redirect
redirect_to :back, alert: t('.match_not_found')
end
end
end
In my index action, I have the following code:
#hotels = Hotel.where(lang: request.headers['Accept-Language']).includes(:contacts)
raise ActiveRecord::RecordNotFound if #hotels.blank?
I am raising the exception because I want it to be handled by an error handling code (based on rescue_from)
Is there a better way to write the code so that it does the same thing, i.e. raise the exception? I can do first! (notice the bang) when retrieving a single record, but as for collections, it seems like there is no way to do the same thing (no where!, all! ...)
Does it make sense at all?
In your controller you can add before_filter
before_filter :check_hotels, :only => [:index]
def index
end
private
def check_hotels
#hotels = Hotel.where(lang: request.headers['Accept-Language']).includes(:contacts)
redirect_to root_path, :notice => "No hotels present." if #hotels.blank?
end
Ofcourse you can give any path othet than root_path, its just an example I have shown
class HotelsController < ApplicationController
rescue_from ActiveRecord::RecordNotFound, with: :blank_list
private
def blank_list
logger.error "No Hotel Found With #{request.headers['Accept-Language']}"
redirect_to root_path, notice: 'No hotels present'
end
end
I'm using Rails 3.2.3 with ActiveResource.
I have an issue in production that says:
ActiveResource::ResourceNotFound: Failed. Response code = 404. Response message = Not Found.
So I tried to treat it the same way I treat ActiveRecord::RecordNotFound:
class ApplicationController < ActionController::Base
protect_from_forgery
rescue_from ActiveRecord::RecordNotFound do |e|
render_404
end
rescue_from ActiveResource::ResourceNotFound do |e|
render_404
end
def render_404
respond_to do |type|
type.html { render template: 'shared/404_not_found', layout: 'application', status: '404 Not Found' }
type.all { render nothing: true, status: '404 Not Found' }
end
end
end
But now, when I deploy, I get an error telling me that:
/apps/com.example/shared/bundle/ruby/1.9.1/gems/activeadmin-0.4.3/lib/active_admin/namespace.rb:191:in `eval': uninitialized constant ActiveResource::ResourceNotFound (NameError)
I don't really get it. I tried with a if defined?(ActiveResource::ResourceNotFound) but then it falls back to the previous behavior.
Any idea of how to treat this issue ?
Thanks !
EDIT: For the moment I used the following code but I'm not really happy with it.
rescue_from Exception do |e|
e.is_a?(ActiveResource::ResourceNotFound) ? render_404 : raise
end
Heh, ignore my comment I figured out a solution:
rescue_from "ActiveResource::ResourceNotFound" do |e|
render_404
end
Put the exception in quotes so it doesn't try to evaluate it on startup (when, I assume, ActiveResource hasn't loaded yet)
I handle RecordNotFound error in my application_controller.rb as follow:
rescue_from ActiveRecord::RecordNotFound, :with => :record_not_found
private
def record_not_found
flash[:error] = "Oops, we cannot find this record"
redirect_to :back
end
But I would like to get more information, such as class/table name of which record was not found.
How should I go about it?
Thank you.
I had some success with this:
# in app/controllers/application_controller.rb
rescue_from ActiveRecord::RecordNotFound, with: :record_not_found
def record_not_found exception
result = exception.message.match /Couldn't find ([\w]+) with 'id'=([\d]+)/
# result[1] gives the name of the model
# result[2] gives the primary key ID of the object that was not found
end
HTH
EDIT: Whitespace error removed at the end of the Regex. Thanks to the commenters. :)
You can define a parameter in your rescue handler and exception will be passed there.
def record_not_found exception
flash[:error] = "Oops, we cannot find this record"
# extract info from exception
redirect_to :back
end
If you can't get that info from the exception, you're out of luck (I think).
Say for example,
begin
#user = User.find(params[:id])
rescue ActiveRecord::RecordNotFound
flash[:notice] = "#No such record in User for id :: {params[:id]} on #{action_name}"
end
UPDATE
flash[:notice] = t('flash.recordnotfound',:class_name => self.class.name, :column_name => params[:id], :action_name => action_name)
Now in your config/locales/en.yml (this would help translate, refer to i18n here)
flash:
recordnotfound: "Sorry, no record od %{column_name} in class %{class_name} was found on you action %{action_name}"
If you do not want to use locales just put up this information in flash[:notice] itself.
More dynamic ?
Write a function and use the same flash [:notice] there. Wont hurt at all.
want more data ?
Heres a quick solution, i always <%= params%> in my views to know easily whats going and whats coming. You can then open your rails console and play along with different actions and so on.
user = User.new
user.save
user.errors.messages
All of this is good enough data, i think.
Good luck.
Once you instantiate the model, you can check something like.
human = Human.new
human.errors
Check this in rails console so you could play with it and use it in the main controller.
rescue_from ActiveRecord::RecordNotFound do |exception|
raise ActiveRecord, exception.message, exception.backtrace
end
EDIT
Make sure you the application controller extends the base.
class ApplicationController < ActionController::Base
rescue_from Exception, :with => :record_not_found
private
def record_not_found(e)
flash[:error] = "Oops, we cannot find this record" + e.message
redirect_to :back
end
end
I'd like to 'fake' a 404 page in Rails. In PHP, I would just send a header with the error code as such:
header("HTTP/1.0 404 Not Found");
How is that done with Rails?
Don't render 404 yourself, there's no reason to; Rails has this functionality built in already. If you want to show a 404 page, create a render_404 method (or not_found as I called it) in ApplicationController like this:
def not_found
raise ActionController::RoutingError.new('Not Found')
end
Rails also handles AbstractController::ActionNotFound, and ActiveRecord::RecordNotFound the same way.
This does two things better:
1) It uses Rails' built in rescue_from handler to render the 404 page, and
2) it interrupts the execution of your code, letting you do nice things like:
user = User.find_by_email(params[:email]) or not_found
user.do_something!
without having to write ugly conditional statements.
As a bonus, it's also super easy to handle in tests. For example, in an rspec integration test:
# RSpec 1
lambda {
visit '/something/you/want/to/404'
}.should raise_error(ActionController::RoutingError)
# RSpec 2+
expect {
get '/something/you/want/to/404'
}.to raise_error(ActionController::RoutingError)
And minitest:
assert_raises(ActionController::RoutingError) do
get '/something/you/want/to/404'
end
OR refer more info from Rails render 404 not found from a controller action
HTTP 404 Status
To return a 404 header, just use the :status option for the render method.
def action
# here the code
render :status => 404
end
If you want to render the standard 404 page you can extract the feature in a method.
def render_404
respond_to do |format|
format.html { render :file => "#{Rails.root}/public/404", :layout => false, :status => :not_found }
format.xml { head :not_found }
format.any { head :not_found }
end
end
and call it in your action
def action
# here the code
render_404
end
If you want the action to render the error page and stop, simply use a return statement.
def action
render_404 and return if params[:something].blank?
# here the code that will never be executed
end
ActiveRecord and HTTP 404
Also remember that Rails rescues some ActiveRecord errors, such as the ActiveRecord::RecordNotFound displaying the 404 error page.
It means you don't need to rescue this action yourself
def show
user = User.find(params[:id])
end
User.find raises an ActiveRecord::RecordNotFound when the user doesn't exist. This is a very powerful feature. Look at the following code
def show
user = User.find_by_email(params[:email]) or raise("not found")
# ...
end
You can simplify it by delegating to Rails the check. Simply use the bang version.
def show
user = User.find_by_email!(params[:email])
# ...
end
The newly Selected answer submitted by Steven Soroka is close, but not complete. The test itself hides the fact that this is not returning a true 404 - it's returning a status of 200 - "success". The original answer was closer, but attempted to render the layout as if no failure had occurred. This fixes everything:
render :text => 'Not Found', :status => '404'
Here's a typical test set of mine for something I expect to return 404, using RSpec and Shoulda matchers:
describe "user view" do
before do
get :show, :id => 'nonsense'
end
it { should_not assign_to :user }
it { should respond_with :not_found }
it { should respond_with_content_type :html }
it { should_not render_template :show }
it { should_not render_with_layout }
it { should_not set_the_flash }
end
This healthy paranoia allowed me to spot the content-type mismatch when everything else looked peachy :) I check for all these elements: assigned variables, response code, response content type, template rendered, layout rendered, flash messages.
I'll skip the content type check on applications that are strictly html...sometimes. After all, "a skeptic checks ALL the drawers" :)
http://dilbert.com/strips/comic/1998-01-20/
FYI: I don't recommend testing for things that are happening in the controller, ie "should_raise". What you care about is the output. My tests above allowed me to try various solutions, and the tests remain the same whether the solution is raising an exception, special rendering, etc.
You could also use the render file:
render file: "#{Rails.root}/public/404.html", layout: false, status: 404
Where you can choose to use the layout or not.
Another option is to use the Exceptions to control it:
raise ActiveRecord::RecordNotFound, "Record not found."
The selected answer doesn't work in Rails 3.1+ as the error handler was moved to a middleware (see github issue).
Here's the solution I found which I'm pretty happy with.
In ApplicationController:
unless Rails.application.config.consider_all_requests_local
rescue_from Exception, with: :handle_exception
end
def not_found
raise ActionController::RoutingError.new('Not Found')
end
def handle_exception(exception=nil)
if exception
logger = Logger.new(STDOUT)
logger.debug "Exception Message: #{exception.message} \n"
logger.debug "Exception Class: #{exception.class} \n"
logger.debug "Exception Backtrace: \n"
logger.debug exception.backtrace.join("\n")
if [ActionController::RoutingError, ActionController::UnknownController, ActionController::UnknownAction].include?(exception.class)
return render_404
else
return render_500
end
end
end
def render_404
respond_to do |format|
format.html { render template: 'errors/not_found', layout: 'layouts/application', status: 404 }
format.all { render nothing: true, status: 404 }
end
end
def render_500
respond_to do |format|
format.html { render template: 'errors/internal_server_error', layout: 'layouts/application', status: 500 }
format.all { render nothing: true, status: 500}
end
end
and in application.rb:
config.after_initialize do |app|
app.routes.append{ match '*a', :to => 'application#not_found' } unless config.consider_all_requests_local
end
And in my resources (show, edit, update, delete):
#resource = Resource.find(params[:id]) or not_found
This could certainly be improved, but at least, I have different views for not_found and internal_error without overriding core Rails functions.
these will help you...
Application Controller
class ApplicationController < ActionController::Base
protect_from_forgery
unless Rails.application.config.consider_all_requests_local
rescue_from ActionController::RoutingError, ActionController::UnknownController, ::AbstractController::ActionNotFound, ActiveRecord::RecordNotFound, with: lambda { |exception| render_error 404, exception }
end
private
def render_error(status, exception)
Rails.logger.error status.to_s + " " + exception.message.to_s
Rails.logger.error exception.backtrace.join("\n")
respond_to do |format|
format.html { render template: "errors/error_#{status}",status: status }
format.all { render nothing: true, status: status }
end
end
end
Errors controller
class ErrorsController < ApplicationController
def error_404
#not_found_path = params[:not_found]
end
end
views/errors/error_404.html.haml
.site
.services-page
.error-template
%h1
Oops!
%h2
404 Not Found
.error-details
Sorry, an error has occured, Requested page not found!
You tried to access '#{#not_found_path}', which is not a valid page.
.error-actions
%a.button_simple_orange.btn.btn-primary.btn-lg{href: root_path}
%span.glyphicon.glyphicon-home
Take Me Home
routes.rb
get '*unmatched_route', to: 'main#not_found'
main_controller.rb
def not_found
render :file => "#{Rails.root}/public/404.html", :status => 404, :layout => false
end
<%= render file: 'public/404', status: 404, formats: [:html] %>
just add this to the page you want to render to the 404 error page and you are done.
I wanted to throw a 'normal' 404 for any logged in user that isn't an admin, so I ended up writing something like this in Rails 5:
class AdminController < ApplicationController
before_action :blackhole_admin
private
def blackhole_admin
return if current_user.admin?
raise ActionController::RoutingError, 'Not Found'
rescue ActionController::RoutingError
render file: "#{Rails.root}/public/404", layout: false, status: :not_found
end
end
Raising ActionController::RoutingError('not found') has always felt a little bit strange to me - in the case of an unauthenticated user, this error does not reflect reality - the route was found, the user is just not authenticated.
I happened across config.action_dispatch.rescue_responses and I think in some cases this is a more elegant solution to the stated problem:
# application.rb
config.action_dispatch.rescue_responses = {
'UnauthenticatedError' => :not_found
}
# my_controller.rb
before_action :verify_user_authentication
def verify_user_authentication
raise UnauthenticatedError if !user_authenticated?
end
What's nice about this approach is:
It hooks into the existing error handling middleware like a normal ActionController::RoutingError, but you get a more meaningful error message in dev environments
It will correctly set the status to whatever you specify in the rescue_responses hash (in this case 404 - not_found)
You don't have to write a not_found method that needs to be available everywhere.
To test the error handling, you can do something like this:
feature ErrorHandling do
before do
Rails.application.config.consider_all_requests_local = false
Rails.application.config.action_dispatch.show_exceptions = true
end
scenario 'renders not_found template' do
visit '/blah'
expect(page).to have_content "The page you were looking for doesn't exist."
end
end
If you want to handle different 404s in different ways, consider catching them in your controllers. This will allow you to do things like tracking the number of 404s generated by different user groups, have support interact with users to find out what went wrong / what part of the user experience might need tweaking, do A/B testing, etc.
I have here placed the base logic in ApplicationController, but it can also be placed in more specific controllers, to have special logic only for one controller.
The reason I am using an if with ENV['RESCUE_404'], is so I can test the raising of AR::RecordNotFound in isolation. In tests, I can set this ENV var to false, and my rescue_from would not fire. This way I can test the raising separate from the conditional 404 logic.
class ApplicationController < ActionController::Base
rescue_from ActiveRecord::RecordNotFound, with: :conditional_404_redirect if ENV['RESCUE_404']
private
def conditional_404_redirect
track_404(#current_user)
if #current_user.present?
redirect_to_user_home
else
redirect_to_front
end
end
end