DEV Community

Augusts Bautra
Augusts Bautra

Posted on

Custom `RoutingError` handling in Rails

Today I was working on improvements to our Rails app monitoring, specifically, we wanted to get some data on what paths without underlying controller bots are making requests to.

As you know, attempting to navigate to some random path raises an ActionController::RoutingError which is then rescued and turned into a 404 response for users. So, where do we hook into for custom logging?

The answer is a special configuration option exceptions_app.

# in config/application.rb
config.exceptions_app = ->(env) do
  exception = env["action_dispatch.exception"]

  if exception.is_a?(ActionController::RoutingError)
    ErrorsController.action(:route_not_found).call(env)
  else
    # fall back to Rails' default for all other errs
    ActionDispatch::PublicExceptions.new(Rails.public_path).call(env)
  end
end
Enter fullscreen mode Exit fullscreen mode

Now you can TDD a regular controller action to handle any custom behaviors such as logging or a custom error page as needed.

A little note, be sure to access request.original_fullpath, rather than request.fullpath, because Rails internals will have set the fullpath to /404.

Top comments (0)