notification all errors and keep different rescues
我正在尝试发送所有rails错误作为通知,而不会打扰其他救援。
ApplicationController中:
1 2 3 4 5 6 7 8 9 10 11 | class ApplicationController < ActionController::Base around_filter :notify_errors def notify_errors begin yield rescue => e Notification.send_to(:admin, e) end end end |
SomeController功能:
1 2 3 4 5 6 | def send_date date = Date.strptime('10/100/2013', '%m/%d/%Y') render json: {success: true, date: date} rescue ArgumentError render json: {success: false, msg: 'Bad date'} end |
我得到了"坏日期"json而不是
再次提出你的例外情况。
1 2 3 4 5 6 7 | def send_date date = Date.strptime('10/100/2013', '%m/%d/%Y') render json: {success: true, date: date} rescue ArgumentError => e render json: {success: false, msg: 'Bad date'} raise e end |
Is there a way to make it easier for each reraise error? A global solution or a function?
你可以monkeypatch
1 2 3 4 5 6 7 8 9 10 | module RaiseNotify def raise(msg_or_exc, msg=msg_or_exc, trace=caller) Notification.send_to(:admin, msg_or_exc) if msg_or_exc.kind_of? StandardError fail msg_or_exc, msg=msg_or_exc, trace end end module Kernel include RaiseNotify end |
我没有测试过这个,它可能会超出Rails的影响,我认为这是一个坏主意! 就个人而言,我只是在初始
1 2 3 4 5 6 7 | def send_date date = Date.strptime('10/100/2013', '%m/%d/%Y') render json: {success: true, date: date} rescue ArgumentError => e Notification.send_to(:admin, e) render json: {success: false, msg: 'Bad date'} end |
这可以通过以下方法缩短:
1 2 3 4 5 6 | def rescue_with_notify error_type=ArgumentError *yield rescue error_type => e Notification.send_to(:admin, e) [nil,false] end |
我们的想法是包装您想要检查的内容,并使用数组进行响应,其结尾将是"成功"标志。
1 2 3 4 5 6 7 8 | def send_date date_string date,success = rescue_with_notify do Date.strptime(date_string, '%m/%d/%Y') end success = true if success.nil? date ||="Bad date" render json: {success: success, date: date} end |
但这增加了复杂性,可能还有额外的线条。 我会坚持将通知代码粘贴到救援条款中,以及何时需要。