In a classic Rails app I tried to handle errors with a custom controller redirecting to the root_path with a flash message.
routes:
match "/404", :to => "errors#not_found", :via => :all
match "/500", :to => "errors#internal_server_error", :via => :all
Error controller:
class ErrorsController < Admin::AdminController
def not_found
redirect_to admin_path, notice: "Sorry, reccord not found"
end
def internal_server_error
redirect_to root_path, notice: "Sorry, something went wrong"
end
end
The error redirect_to admin_path or root_path (I've tried other paths to be sure it's not related)
The admin path just show a dashboard:
class Admin::StaticController < Admin::AdminController
def dashboard
flash.keep
byebug
end
end
I tried to add the flash.keep even if there's no multiple redirection. Byebug stops the process to help to see what's happening but flash notice appears nil at this point.
Logs (cleaned a little):
Started GET something_not_possible_to_get
Completed 404 Not Found in 13ms (ActiveRecord: 2.3ms)
ActiveRecord::RecordNotFound
Processing by ErrorsController#not_found as HTML
Redirected to the_path
Started GET "/" (root_path)
ByeBug stopping here and notice is nil
continue just render the page as expected but without the notice
What I'm trying to achieve is to redirect users getting error (404 or 500) to the root_path or another path, let them know something went wrong with a notification message (flash) but without blocking them on the classic Rails error page. Then I could be able to implement internal errors handling (let say email to the admin/owner of the app for instance).
I tried the keep.flash without success.
Why the notice message is dropped? And why this is happening only with errors (I have a lot of redirect_to with notice that are working fine)?
Redirected to root_path
happens when the user encounters a 500 error, but in your log it says 404 error. – Sahil