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?
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With