6

I have an action that searches records based on a url parameter. The url for the action looks something like this:

http://domain.com/records/filter/<filtercode>

If the user enters an incorrect filtercode, I would like to app to

  • raise an error so that Hoptoad will report to error to me.
  • render a 404 instead of a 500 in production env.

I understand that certain Rails errors such as ActiveRecord::NotFound and ActionController:RoutingError will render 404 in production env. So what I like to do is raise this error when a user enters an invalid filtercode in the url.

Now, my question: what's the ideal error to raise in this type of situation? Is there a list of Rails errors/exceptions in the net?

Ryan Bigg
  • 106,965
  • 23
  • 235
  • 261
gsmendoza
  • 1,394
  • 1
  • 13
  • 31
  • possible duplicate of [How to redirect to a 404 in Rails?](http://stackoverflow.com/questions/2385799/how-to-redirect-to-a-404-in-rails) – Brad Werth Sep 02 '14 at 15:54

3 Answers3

5

You're looking for

ActionController::RoutingError

I like to do this in my application_controller:

  def not_found
    raise ActionController::RoutingError.new('Not Found')
  end

Then in other controllers, say pages#show for example, I can do:

def show
  unless @page = Page.find_by_permalink(params[:permalink])
    not_found
  end
end
tybro0103
  • 48,327
  • 33
  • 144
  • 170
3

You should be catching any sort of error thrown by Rails as none of them are made to be user-facing... When an exception bubbles up to the HTTP response, it will always manifest as HTTP 500.

What is perfectly normal is to catch the exception and handle it by setting the HTTP status to 404 and output your own error perhaps saying "we searched for this, but didn't find anything". Or, if security is a concern, just say "not found" in a really fancy way.

Alexander Trauzzi
  • 7,277
  • 13
  • 68
  • 112
2

If it searches records and doesn't find any the logical way would be to use the ActiveRecord::NotFound wouldn't it?

nitecoder
  • 5,496
  • 1
  • 28
  • 35