Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Wrap all controller actions in a begin rescue for error logging

I've recently set up Rollbar for my rails app. It's reporting the errors but not always with context. In order to get context you need to catch the exception and pass in the error

begin
  # code...
rescue => e
  Rollbar.error(e)

Is there a rails way to generically catch exceptions with context?

Maybe you wrap application controller with something? In Django you can subclass a view...

like image 735
user2954587 Avatar asked Jan 08 '23 15:01

user2954587


1 Answers

Assuming all your controllers inherit from ApplicationController, you can use rescue_from in your ApplicationController to rescue any errors in any controller.

ApplicationController < ActionController::Base

  rescue_from ActiveRecord::RecordNotFound do |exception|
    message = "Couldn't find a record."
    redirect_to no_record_url, info: message
  end

end

You can have multiple rescue_from clauses for different error classes, but note that they're invoked in reverse order, so a generic rescue_from should be listed before others...

ApplicationController < ActionController::Base

  rescue_from do |exception|
    message = "some unspecified error"
    redirect_to rescue_message_url, info: message
  end

  rescue_from ActiveRecord::RecordNotFound do |exception|
    message = "Couldn't find a record."
    redirect_to rescue_message_url, info: message
  end

end
like image 156
SteveTurczyn Avatar answered Jan 17 '23 12:01

SteveTurczyn