Alex Wayne
Alex Wayne

Reputation: 187222

Catch all route and 404 in rails 2.x

I have a CorsController whose job it is to respond crossdomain ajax headers (if the Origin is allows) whenever my application receives an OPTIONS request. But because I don't know exactly where that OPTIONS request will land, I have a catchall route at the top of my routes file set to catch any OPTIONS request to any path.

map.cors '*path',
  :controller => 'cors',
  :action => 'index',
  :conditions => { :method => :options }

For actual OPTIONS requests, this works great. The problem comes in when the app should be serving a 404 Not Found.

Now what happens when I load /no/404/for/you (a path that my application does not handle a route for), I no longer get a 404. Instead this route get's activated and I get a 405 Method Not Allowed. This is causing our logs to be filled with errors that aren't really errors, and monitoring (like New Relic) to send out panic emails about error rates, when in reality everything is just fine.

It appears to see that the path matches, but the :conditions does not, and raises an exception. What interesting is that it appears the route handling is a 2 pass process. This cors route, at the top of my routes file, only triggers if there is an OPTIONS request (good) or if no other route declare after it matches and there is no static file at that path (bad).

Question:

How can I get this catch-all route to hit my controller for all OPTIONS requests, without it also intercepting and throwing errors about otherwise unmatched routes via GET, POST, PUT and DELETE?

And I need to do this, sadly, in Rails 2.x.

Upvotes: 0

Views: 656

Answers (1)

Benoît
Benoît

Reputation: 15010

So you say

This cors route, at the top of my routes file, only triggers if there is an OPTIONS request (good) or if no other route declare after it matches and there is no static file at that path (bad).

You could add a route at the very end of your routes.rb that would match everything else and just return 404.

As your said it is kind of hacky but I don't see any other way to complete your catchall route at the top. Maybe someone will come up with something else.

Upvotes: 2

Related Questions