How to catch top level failures on an EventMachine server?

守給你的承諾、 提交于 2019-12-01 02:02:07

问题


I have an EventMachine server that I am monitoring with monit. Sometimes it crashes, and I am trying to figure out why, but it is unclear to me how I can just log all top level failures. I tried code like this:

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 does not seem to ever catch errors. I suspect it might be something like running out of memory, which I am tracking separately, but still I would like this server to log its proximate cause of failure if possible.


回答1:


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

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

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

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 in your MyServer, then whenever you want to raise an error, call fail.



来源:https://stackoverflow.com/questions/7628232/how-to-catch-top-level-failures-on-an-eventmachine-server

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!