如何在 EventMachine 实现中捕获异常? [英] How do you catch exceptions in an EventMachine implementation?

查看:27
本文介绍了如何在 EventMachine 实现中捕获异常?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个与 另一个帖子类似的问题,我已经尝试了给定的解决方案,但无济于事.

I have a similar problem to this other post and I've tried the given solutions but to no avail.

我的项目是一个 Ruby 机器人,它使用 Blather 库连接到 Jabber 服务器.问题是当服务器出现问题并且 Blather 生成异常时,整个程序退出,我没有机会捕获异常.

My project is a Ruby bot that uses the Blather library to connect to a Jabber server. The problem is that when there is a problem with the server and Blather generates an exception the whole program exits and I have no opportunity to catch the exception.

这是一些显示问题的简单代码.本地主机上没有运行 Jabber 服务器,因此 Blather 客户端抛出异常.我的印象是 EM.error_handler{} 能够拦截它,但我从未看到 **** ERROR 消息,程序就停止了.:(

Here is some simple code that shows the problem. There is no Jabber server running on localhost so the Blather client throws an exception. I was under the impression that EM.error_handler{} would be able to intercept it but I never see the **** ERROR message and the program just stops. :(

#!/usr/bin/env ruby
require 'rubygems'
require 'blather/client/client'

EM.run do
  EM.error_handler { puts " **** ERROR " }

  Blather::Stream::Client.start(
    Class.new {
    }.new, 'echo@127.0.0.1', 'echo')
end

我认为问题在于 Blather 也使用 EventMachine,并且可能正在调用 EM.stop,这会导致外部 EM 实例停止.

I think the problem is that Blather also uses EventMachine and maybe is calling EM.stop, which causes the external EM instance to stop.

推荐答案

异常和异步编程不是朋友,因此它们可能很难正确处理.在同步模型中,可以通过对可能产生异常的代码块使用 rescue 来捕获异常,但是一旦创建了回调方法,该块就需要自己的异常处理,因为它将在外部运行那个上下文.

Exceptions and asynchronous programming are not friends, so they can be tricky to handle properly. In the synchronous model, an exception can be caught by using rescue on a block of code that may produce exceptions, yet once you create a callback method, that block needs its own exception handling since it will run outside of that context.

希望 error_handler 会捕获您的异常,但如果您有其他线程可能无法捕获它们.

Hopefully the error_handler will catch your exception, but if you have other threads involved that may not be able to capture them.

您可以随时使用monkeypatch EventMachine.stop_event_loopEventMachine.stop_server 来查看是否正在调用该方法.

You could always monkeypatch EventMachine.stop_event_loop and EventMachine.stop_server to see if that's the method being called.

这篇关于如何在 EventMachine 实现中捕获异常?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆