Rails rake 任务调用错误捕获

Rails rake task invoke error catching

我有一个 rails 代码片段,它从一个模型中生成一个 rake 文件。

Rake.application.rake_require '../../lib/tasks/master_load'
fork do
  results = capture_stdout {Rake.application['db:seed:excel:to_yaml'].invoke}
end

capture_stdout用于打印日志

def self.capture_stdout
    s = StringIO.new
    oldstdout = $stdout
    $stdout = s
    yield
    s.string
    Rails.logger.info "#{s.string}"
  ensure
    $stdout = oldstdout
end

它可以工作,但是当耙子遇到错误并失败时。 它默默地失败了。 有没有办法知道是否发生错误并可能获取错误日志?

使用 rescue 捕捉并处理错误

def self.capture_stdout
    s = StringIO.new
    oldstdout = $stdout
    $stdout = s
    yield
    s.string
    Rails.logger.info "#{s.string}"
  rescue Exception => e
    # handle e - exception object 
  ensure
    $stdout = oldstdout
  end

确保在这种情况下在异常处理后默默地进行操作