Fab*_*bio 15 error-handling rake exception-handling ruby-on-rails exception-notification
我有一个简单的rails应用程序,带有一些控制器和一些rake任务.由gem配置的cron执行几个任务.
我的任务之一是每天执行,有时会引发异常,默认情况下我会收到cron的警告
rake aborted!
undefined method `parameterize' for nil:NilClass
Tasks: TOP => mailboxes:clean_processed
(See full trace by running task with --trace)
Run Code Online (Sandbox Code Playgroud)
我想调试正在发生的事情,因此我刚刚在我的这行中安装了这个异常通知 gemGemfile
gem "exception_notification", "~> 2.4.1", :require => 'exception_notifier'
Run Code Online (Sandbox Code Playgroud)
并在我的application.rb文件中配置它
# enable exception notification
config.middleware.use ExceptionNotifier,
:email_prefix => "[MyAppName] ",
:sender_address => %{"notifier" <report@example.com>},
:exception_recipients => %w{me@example.com}
Run Code Online (Sandbox Code Playgroud)
由于这个gem是一个机架中间件,它只适用于Web请求而不适用于rake任务.我也想为rake任务启用它,我找到了这个工作的要点.
它工作,但它不是DRY,我需要在该方法中重复gem配置,我还需要更改我所有的rake任务,将它们的语句封装在一个块中,如同
exception_notify { actual_task_code }
Run Code Online (Sandbox Code Playgroud)
有没有更好的方法来解决这个问题?
PS如果我需要更改通知gem不会有问题,因为我只为我的项目添加了几行代码.
PPS我知道我也可以更改crontab中的rake行来添加一个--trace选项,但是我不喜欢那个解决方案,导致异常通知程序imho是一个更好的解决方案,它也有助于Web代码.
更新我刚刚发现了这个相关的问题:delayed_not的exceptions_notification但两个答案都使用了类似的技巧.
我将尝试像Airbrake(以前称为hoptoad)或Exceptional这样的在线服务,但它们都是付费服务......
更新2:我尝试了Airbrake App,非常好的应用程序,但它遇到同样的问题,我仍然需要破解Rakefile来通知rake任务的异常.然而,hack不那么干,因为你只需要这个代码:
# notify exceptions
def exception_notify
yield
rescue Exception => exception
HoptoadNotifier.notify exception
raise exception
end
Run Code Online (Sandbox Code Playgroud)
无需重复任何配置参数.我认为我不能做得比这更好,以获得rake任务中的异常通知.
Rec*_*nic 14
在config/initializers中创建一个task.rb文件,其中有猴子补丁Rake :: Task#execute包含exception_notify的功能:
module Rake
class Task
alias :orig_execute :execute
def execute(args=nil)
orig_execute(args)
rescue Exception => exception
# Exception notification stuff
end
end
end
Run Code Online (Sandbox Code Playgroud)
使用Rails 3.0.12,Rake 0.9.2.2进行测试.