通知所有错误并保留不同的救援

notification all errors and keep different rescues

我正在尝试发送所有 rails 错误作为通知,不打扰其他救援

ApplicationController:

class ApplicationController < ActionController::Base
around_filter :notify_errors

  def notify_errors
    begin
      yield
    rescue => e
      Notification.send_to(:admin, e)
    end
  end
end

SomeController 函数:

  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

我得到 "Bad date" json 但没有 Notification.send_to(:admin, e).

再次提出你的例外。

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 raise.

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,我认为这是个坏主意!就个人而言,我只是在初始 rescue 子句中调用通知代码。

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

这可以通过以下方法缩短:

def rescue_with_notify error_type=ArgumentError
  *yield 
rescue error_type => e      
  Notification.send_to(:admin, e)
  [nil,false]
end   

我们的想法是包装您要检查的内容,并用一个数组进行响应,数组的末尾是 "success" 标志。

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  

但这增加了复杂性,可能 额外的行在 return 中花费很少。我会坚持在需要时将通知代码粘贴到救援条款中。