简体   繁体   English

如何在Rails3的config / initializers下捕获所有ActiveRecord :: Errors

[英]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. 我试图配置我的应用程序以从我的应用程序中的任何ActiveRecord对象打印错误。 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 在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, 我相信您希望将所有AR错误集中在一处,

One method would be using rescue_from . 一种方法是使用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 . 更合适的方法是将其包含在模块中并将其includeApplciationController

HTH 高温超导

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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