Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Catch all exceptions in rails controller's before_action

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.

like image 532
pawel7318 Avatar asked Apr 08 '14 14:04

pawel7318


1 Answers

"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.

like image 170
drKreso Avatar answered Oct 17 '22 15:10

drKreso