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

发布于 2024-12-11 00:27:44 字数 512 浏览 0 评论 0原文

现在我们的应用程序正在 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

Right now our application is running on Heroku, and in order to save restarts and possible latency the application is designed to cache all errors and send them to stderr and just server a stale cache until the issue is resolved by another push. This prevents application takedown...

However, the logs keep filling up excessively with entire traces which we don't want, so I built a little snippet (that is partially stolen from Rails) to parse caller and only send that line, however with errors being sent from a rescue, we get the wrong line so I was wondering how I could get the caller or the caller or if there was a better way to handle this situation. Here is the snippet:

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

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

ˉ厌 2024-12-18 00:27:44

如果我明白了,你想引发一个异常,并从调用者的调用者开始进行回溯。这样做:

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

If I get it, you want to raise a exception with a backtrace that begins on the caller of the caller. Do it:

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
囍笑 2024-12-18 00:27:44

caller 返回一个数组,您可以通过查看后面的元素来更深入地了解调用堆栈(请注意,您正在查看 caller[1]

caller returns an array and you can go deeper into the call stack by looking at it's later elements (note that you're looking at caller[1])

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文