Raising a more approprriate error when rescuing RoutingError

Hello,

I’d like to rescue ActionController::RoutingError and, depending on
context, raise a more appropriate error.

A slightly contrived example: I’ve been seeing a lot of requests for
.php files. There’s no PHP on my server, and all of these requests are
script kiddie scans looking for known-exploitable scripts. So, in this
special case, I want to raise something like Ruby’s built-in
SecurityError instead. This would make my logged exceptions more useful.

So I tried this:

in application.rb

def rescue_action_in_public(e)
case e
when ActionController::RoutingError
if request.path =~ /.php$/
raise SecurityError, “PHP request”
else
super
end
# [snip: handle more exceptions here]
else
super
end
end

Unfortunately, this blows up and I get the failsafe 500:

DISPATCHER FAILSAFE RESPONSE (has cgi) Sat Jun 23 04:51:28 -0700 2007
Status: 500 Internal Server Error
No route matches “/test.php” with {:method=>:get}
[snip: usual stack trace for a RoutingError]

The strange thing is, if I try this with an error other than
RoutingError, it works as expected. (For example, substituting in
ActiveRecord::RecordNotFound, and a request like /users/99999.php, with
routing to match ‘/users/:id.:format’.)

I suppose this might have something to do with how early a RoutingError
gets raised in the request cycle. But, I can confirm that
rescue_action_in_public is getting called (log.debug statement in there
works as expected).

Thoughts? Thanks for reading, I know that was long.

Chris K.
http://kampers.net