Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ActiveRecord::RecordNotFound raises 404 instead of 500

We had an action that was essentially failing silently in production because it was raising an ActiveRecord::RecordNotFound error, which Rails treats as a 404 error instead of a 500 error- meaning it wasn't being captured by our error logger.

I don't like that Rails maps certain errors to 404s- I think it should be up to the developer to decide whether a URL is invalid, or whether the failure to retrieve an record is an application error.

How do we ensure all Rails errors are treated as 500 errors?

like image 933
Yarin Avatar asked Nov 28 '22 07:11

Yarin


1 Answers

First off, if you can manually notify your error logger of the error, that would probably be the best thing to do. Making Rails return a different HTTP status code might break other parts of your application.

However, if you absolutely must do so, you can instruct Rails not to return a 404 by removing the corresponding entry from the rescue responses hash. You could do this in an initializer:

# config/initializers/rescue_responses_overrides.rb
ActionDispatch::ExceptionWrapper.rescue_responses
  .delete('ActiveRecord::RecordNotFound')

Now Rails will send a 500 status code to the browser whenever ActiveRecord::RecordNotFound is raised. You could also remove all entries in a single step:

ActionDispatch::ExceptionWrapper.rescue_responses.clear

To see which other errors Rails returns different status codes for, you can simply print the hash in the Rails console:

pp ActionDispatch::ExceptionWrapper.rescue_responses
like image 165
fivedigit Avatar answered Dec 05 '22 13:12

fivedigit