开发者

How to log exceptions automatically in Rails?

开发者 https://www.devze.com 2023-02-12 07:31 出处:网络
If there is an exception in a controller action and rescue is used, Rails does not show the exception either in the开发者_Go百科 browser (which is O.K), nor does it write the exception to the log file

If there is an exception in a controller action and rescue is used, Rails does not show the exception either in the开发者_Go百科 browser (which is O.K), nor does it write the exception to the log file.

Is there a way to get Rails to write the exception to the log file in this case?

Example:

def some_action
  2/0
rescue
  #this code is called, but Rails does not write the exception to the log
end


You're rescuing the exception, so it won't log it because nothing bad actually happened since it was, in fact, "rescued".

You can put the following code within your rescue block to put an entry in the log:

logger.warn "Exception rescued!"

You can read more about using the logger in the Rails Guides.


I ended up using rescue_from in the ApplicationController, logging the exception message and backtrace, and then using params[:controller] and params[:action] to determine what controller/action to redirect to.

For example, if PostsController#show exception'ed out, I would redirect to PostsController#index from within rescue_from. It's been working so far, so it doesn't seem to be a bad thing to do redirect_to from within rescue_from. Time will let me know, I'm sure! (Just need to make sure that my redirects don't cause some infinite loops!)

And just in someone is interested in this hack (try at your own risk!):

class ApplicationController < ActionController::Base

  def determine_redirect_to_path(controller,action)
    ...
  end

  rescue_from StandardError do |exception|    
    backtrace_size = exception.backtrace.size
    if backtrace_size >= 2 then max_range = 2
    elsif backtrace_size >= 1 then max_range = 1
    end
    if max_range > 0      
      s = "rescued_from:: #{params[:controller]}##{params[:action]}: #{exception.inspect}\n#{exception.backtrace[0..max_range].to_s}\n"
      logger.error s
    end
    redirect_to determine_redirect_to_path(params[:controller],params[:action])
  end      
end  
0

精彩评论

暂无评论...
验证码 换一张
取 消