Open7

ActiveRecord::RecordNotFound の dev と prod での振る舞いの違いを掘る

Ohkubo KOHEIOhkubo KOHEI
class MyException < StandardError
  ActionDispatch::ExceptionWrapper.rescue_responses[name] = :not_found
end

などとすれば、独自 Exception で 500 以外の status_code を返すようになる。また、
config.action_dispatch.show_exceptions = :rescuable
設定の時に request test で例外そのものが飛ばず、ステータスコードのテストができる。
symbol と status code の対応はここらへん
https://github.com/rack/rack/blob/v3.1.8/lib/rack/utils.rb#L505-L506

Ohkubo KOHEIOhkubo KOHEI

dev 環境で表示される画面を作ってるのはこいつ
https://github.com/rails/rails/blob/main/actionpack/lib/action_dispatch/middleware/debug_exceptions.rb
prod 環境では public/500.html とかを表示するが、その制御はこいつ
https://github.com/rails/rails/blob/main/actionpack/lib/action_dispatch/middleware/public_exceptions.rb

ここで並んでスタックに積まれる。
https://github.com/rails/rails/blob/v7.2.2.1/railties/lib/rails/application/default_middleware_stack.rb#L58-L59
https://github.com/rails/rails/blob/v7.2.2.1/railties/lib/rails/application/default_middleware_stack.rb#L131-L133

DebugExceptions は RAILS_ENV に関わらず、常に middleware として読み込まれている。 (一部の controller だけで機能させる、のような設定が可能)
PublicExceptionsconfig.exceptions_app で差し替え可能。

Ohkubo KOHEIOhkubo KOHEI

DebugExceptions が render するスイッチは action_dispatch.show_detailed_exceptions

https://guides.rubyonrails.org/configuring.html#config-consider-all-requests-local

3.2.16 config.consider_all_requests_local
Is a flag. If true then any error will cause detailed debugging information to be dumped in the HTTP response, and the Rails::Info controller will show the application runtime context in /rails/info/properties. true by default in the development and test environments, and false in production. For finer-grained control, set this to false and implement show_detailed_exceptions? in controllers to specify which requests should provide debugging information on errors.