救援中的DRY代码=> e在Rails中的各种模型文件中

Sak*_*ain 2 ruby error-handling model ruby-on-rails dry

在sidekiq_batch.rb中,

def sidekiq_status
  begin
    something    
  rescue => e
    Rails.logger.error("\nRESCUENIL in sidekiq_status #{e.class} #{e.message} in #{e.backtrace}")
    # FIXME RESCUENIL
    nil
  end
end
Run Code Online (Sandbox Code Playgroud)

在checkin.rb中,

def attached_receipt_image
  begin
    something else
  rescue => e
    Rails.logger.error("\nRESCUENIL in attached_receipt_image #{e.class} #{e.message} in #{e.backtrace}")
    # FIXME RESCUENIL
    nil
  end
end
Run Code Online (Sandbox Code Playgroud)

在barcode.rb中,

def receipt_check?
  begin
    some code      
  rescue => e
    Rails.logger.error("\nRESCUENIL in receipt_check #{e.class} #{e.message} in #{e.backtrace}")
    # FIXME RESCUENIL
    nil
  end
end
Run Code Online (Sandbox Code Playgroud)

需要干掉代码.如何在模型中为所有这些方法编写常见的错误记录例程?

tok*_*and 5

你可以为它写一个抽象,但你不能return从那里.你可以写:

def with_log(name)
  begin
    yield
  rescue => exc
    Rails.logger.error("\nRESCUENIL in #{name} #{exc.class} #{exc.message} in #{exc.backtrace}")
    false
  end
end

with_log(:sidekiq_status) do
  something
  true # not needed if something returns a boolean with the success status
end or return
Run Code Online (Sandbox Code Playgroud)

true也可以移动到with_log,这取决于您打算如何使用它.