获取调用者的 Ruby 异常调用者

Jor*_*ell 2 ruby debugging sinatra

现在我们的应用程序正在 Heroku 上运行,为了避免重启和可能的延迟,应用程序被设计为缓存所有错误并将它们发送到 stderr 并只提供一个陈旧的缓存,直到问题通过另一个推送得到解决。这可以防止应用程序删除...

然而,日志一直被我们不想要的整个跟踪过度填满,所以我构建了一个小片段(部分从 Rails 中窃取)来解析调用者并只发送该行,但是从救援中发送错误,我们接错了线路,所以我想知道如何找到来电者或来电者,或者是否有更好的方法来处理这种情况。这是片段:

module StdErr
  def error(message)
    file = 'Unknown'
    line = '0'

    if /^(.+?):(\d+)(?::in `(.*)')?/ =~ caller[1]
      file = $1
      line = $2
    end

    $stderr.puts "ERROR: #{message} on line #{line} of #{file}"
  end
end
Run Code Online (Sandbox Code Playgroud)

Gui*_*nal 5

如果我明白了,您想通过从调用者的调用者开始的回溯引发异常。这样做:

def raise_cc(*args)
  raise(*args)
rescue Exception
  # Raises the same exception, removing the last 2 items
  # from backtrace (this method and its caller). The first
  # will be the caller of the caller of this method.
  raise($!.class, $!.message, $!.backtrace[2..(-1)])
end
Run Code Online (Sandbox Code Playgroud)

  • 你为什么使用“救援对象”?`rescue Exception` 足以捕获所有异常。 (2认同)