Rails 例外
Railsアプリケーション内でエラーがraiseされた際にフレームワークとしてどのように扱われるか?
controllerレイヤ
ユーザーが任意のエラーをハンドリングしたい場合、rescue_fromを使う
https://railsguides.jp/action_controller_overview.html#rescue-from
Rack Middlewareレイヤ
ユーザーが明示的にエラーハンドリングしていない例外
ActionDispatch::ShowExceptionsミドルウェアが処理する
https://railsguides.jp/rails_on_rack.html
https://api.rubyonrails.org/classes/ActionDispatch/ShowExceptions.html
アプリケーションが返すすべての例外をrescueし、config.exceptions_appで設定した例外処理用アプリケーションを呼び出す
https://github.com/rails/rails/blob/23938052acd773fa24068debe56cd892cbf8d868/actionpack/lib/action_dispatch/middleware/show_exceptions.rb#L52
config.exceptions_app
https://railsguides.jp/configuring.html#config-exceptions-app
デフォルトではActionDispatch::PublicExceptionsアプリケーションが設定されている
https://github.com/rails/rails/blob/23938052acd773fa24068debe56cd892cbf8d868/actionpack/lib/action_dispatch/middleware/public_exceptions.rb
カスタムアプリケーションを設定することもできる
動的にエラーページやレスポンスを制御できる
その用途ならrambulance
code:config/application.rb
config.exceptions_app = CustomExceptionsAppWrapper.new(exceptions_app: routes)
code:lib/custom_exceptions_app_wrapper.rb
class CustomExceptionsAppWrapper
def initialize(exceptions_app:)
@exceptions_app = exceptions_app
end
def call(env)
request = ActionDispatch::Request.new(env)
fallback_to_html_format_if_invalid_mime_type(request)
@exceptions_app.call(env)
end
private
def fallback_to_html_format_if_invalid_mime_type(request)
request.formats
rescue ActionDispatch::Http::MimeNegotiation::InvalidType
request.set_header "CONTENT_TYPE", "text/html"
end
end
関連
https://www.youtube.com/watch?v=zcT5GufiQ-0
https://discourse.clean-rails.org/t/topic/364