Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do you catch exceptions in an EventMachine implementation?

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

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.

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, '[email protected]', 'echo')
end

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

like image 450
Richard Hurt Avatar asked Dec 07 '11 13:12

Richard Hurt


1 Answers

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.

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

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

like image 72
tadman Avatar answered Sep 29 '22 23:09

tadman