Alex Rivera | Logout

Catch Unknown action in Rails 3 for custom 404

Asked 2011-09-08T03:34:51.183
12

I want to catch unknown action error in Rails 3, that shows "Unknown Action" error on development and the 404.html on production. I tried putting this rescue_from handler on my ApplicationController (and also on an actual controller, just in case) but I still see the ugly error.

I have custom stuff on the 404, and it can't be plain .html file.

My route:

match '/user/:id/:action', controller: 'users'

The URL I'm accessing: /user/elado/xxx

The rescue_from code:

rescue_from AbstractController::ActionNotFound, :with => :action_not_found

def action_not_found
  render text: "action_not_found"
end

The error in the browser:

Unknown action

The action 'xxx' could not be found for UsersController

And in the console:

Started GET "/user/elado/xxx" for 127.0.0.1 at 2011-09-07 19:16:27 -0700

AbstractController::ActionNotFound (The action 'xxx' could not be found for UsersController):

Tried also rescue_from ActionController::UnknownAction.

Any suggestions? Thanks!

Edit
Report

1 Answer

9

Using a catch all route to handle 404 erros (as @Seth Jackson suggested) has one major drawback: if you use any Rails engines that define their own routes (such as Jammit) their routes will be ignored.

Better and more compliant solution would be to use a Rack middleware that will catch 404 errors. In one of my projects, I've implemented such Rack middleware that reports these errors to Hoptoad. I've based my implementation on this one: https://github.com/vidibus/vidibus-routing_error, but instead of invoking my Rails app again to handle the 404 error, I do it in the Rack middleware and let nginx to show the 404 page.

answered 2011-09-08T07:02:22.007

Your Answer