简体   繁体   中英

How to capture all ActiveRecord::Errors under config/initializersin Rails3

I am trying to configure my applications to print errors from any ActiveRecord object in my app. So that I can avoid printing the error message for each object in all place of transactions. Is there any way to do this?

Need somethind like this

in config/initializers

ActiveRecord::Base.class_eval do
   # For each active_record object in my app
   if self.errors.any?
      puts self.errors.inspect
   end
end

I believe you want to have all the AR errors in one place,

One method would be using rescue_from . Simply you could do something like this in your application controller

class ApplicationController < ActionController::Base 
   protect_from_forgery with: :exception

   #your normal code

   rescue_from Exception do |exeception|
      #check if this is a AR exception
      #if yes then
      #log it in a different log file
      #if not
      # yield (to follow the default exception chain)
   end
end   

more proper way would be to have this in a module and include it in ApplciationController .

HTH

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM