ruby-on-railsrubyactionview

How to get original exception from ActionView::Template::Error


If a template causes an ActiveRecord::RecordNotFound exception to be raised, the original exception is swallowed up by ActionView and turned into an ActionView::Template::Error.

It seems that in Rails 5 there was an original_exception method but that appears to be gone in Rails 6.

I'd like to be able to inspect the cause of the ActionView::Template::Error so I can show better contextual errors.

Is there any way to do so?


Solution

  • If you catch the ActionView::Template::Error, there should be a #cause method defined on it which returns the original exception. Example:

    begin
      begin
        raise ArgumentError
      rescue
        raise RuntimeError
      end
    rescue => e
      puts "#{ e } caused by #{ e.cause }"
    end
    

    prints

    RuntimeError caused by ArgumentError