How to catch top-level errors on an EventMachine server?

I have an EventMachine server that I control with monit. Sometimes it crashes, and I try to understand why, but I don’t understand how I can register all the top-level errors. I tried the code as follows:

begin EventMachine::run do EventMachine::start_server('0.0.0.0', PORT, MyServer) end rescue Exception => e puts "FAILURE: #{e.class}: #{e}" end 

but that never seems to break the bugs. I suspect this may be something like a lack of memory, which I track separately, but still I would like this server to log its closest cause of failure, if possible.

+7
source share
1 answer

If you want a catch-all error handler, try EM.error_handler. Example from docs :

 EM.error_handler{ |e| puts "Error raised during event loop: #{e.message}" } 

You may also need finer error handling, in which case you can use the errback mechanism (see Deferrable ). So, for example, you could have in your loop reactor:

 EventMachine::run do server = EventMachine::start_server('0.0.0.0', PORT, MyServer) server.errback { # handle error thrown by server here } end 

For this to work, include Deferrable on your MyServer, then whenever you want to raise an error, call fail .

+15
source

All Articles