albums_controller.rb:
lass AlbumsController < ApplicationController
before_action :set_album, only: [:show, :edit, :update, :destroy]
def destroy
if @album.destroy
redirect_to albums_url, notice: 'Album was successfully destroyed.'
else
redirect_to albums_url, error: 'Album destroy failed.' # _DEST_
end
end
private
def set_album
@album = Album.find(params[:id]) # _FIND_
end
end
I would like to catch Exception for Album.find()
. According to this I added:
rescue_from Exception, with: :flash_error
# private
def flash_error
flash_message :error, 'Something went wrong..' # _FLASH_
end
I marked some parts above as _FIND_
, _FLASH_
, _DEST_
and I would like to go through all of them in that order. I tried to delete album that doesn't exists to trigger that. I got blank page with URL for albums/(:id) (the one I tried to delete) so I suppose I stuck at _FLASH_
part.
What should I do to call destroy
action (I mean the original one called as rescue_form as it can catch other exceptions for other controller actions as well). And how can get better message than Something went wrong
?
The main goal is to redirect to the correct page (specified at _DEST_
), so maybe there's some better approach.
"rescue_from" callback method "flash_error" is behaving like a normal controller action that from user perspective ends up rendering blank page. In that sense it is not stuck there, it is done there.
In order to "proceed" you need to redirect or render. Notice that exception gets propagated so you can get more details about what happened:
#I am using Rails 3.2 flash notation
def flash_error(exception)
flash[:error] = "#{exception.message} (Something went wrong..)" # _FLASH_
redirect_to albums_url
end
My advice is never to catch all exceptions. In my experience nothing but grief ever came out of it. Imagine if you had exception in index action - that would end up in a loop.
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