Handle exceptions during TURBO_STREAM requests

This commit is contained in:
2024-01-15 01:59:30 +01:00
parent 93929f2c07
commit 9a9a139aa7
3 changed files with 42 additions and 12 deletions

View File

@@ -3,8 +3,19 @@ class ApplicationController < ActionController::Base
before_action :authenticate_user!
class AccessForbidden < StandardError
end
class AccessForbidden < StandardError; end
class ParameterInvalid < StandardError; end
# Exceptions are handled depending on request format:
# * HTML is handled by PublicExceptions, resulting in display of
# 'public/<status-code>.html' template.
# * TURBO_STREAM is handled by method specified below, which writes flash
# message and forces redirect to referer - to display flash and make page
# content consistent with database (which may or may not have been
# modified before exception).
# This requires referer to be available in TURBO_STREAM format. Otherwise
# Turbo will reload 2nd time with HTML format and flashes will be lost.
rescue_from *ActionDispatch::ExceptionWrapper.rescue_responses.keys, with: :rescue_turbo
protected
@@ -23,4 +34,14 @@ class ApplicationController < ActionController::Base
def after_sign_out_path_for(scope)
new_user_session_path
end
private
def rescue_turbo(exception)
raise unless request.format.to_sym == :turbo_stream
message_id = ActionDispatch::ExceptionWrapper.rescue_responses[exception.class.to_s]
flash.alert = t("actioncontroller.exceptions.status.#{message_id}")
redirect_to request.referer
end
end