# Raising a more approprriate error when rescuing RoutingError

**URL:** <https://www.ruby-forum.com/t/raising-a-more-approprriate-error-when-rescuing-routingerror/107573>\
**Category:** Rails\
**Created:** [June 23, 2007, 3:10pm UTC](https://www.ruby-forum.com/t/raising-a-more-approprriate-error-when-rescuing-routingerror/107573 "2007-06-23T15:10:01Z")\
**Posts on this page:** 1\
**Page:** 1

<div class="post-metadata">

**Author:** ![kampers](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/k/54ee81/32.png) [@kampers](https://www.ruby-forum.com/u/kampers)\
**Post date:** [June 23, 2007, 3:10pm UTC](https://www.ruby-forum.com/t/raising-a-more-approprriate-error-when-rescuing-routingerror/107573/1 "2007-06-23T15:10:01Z")

</div>

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](http://kampers.net)
