处理分叉进程中的异常

时间:2016-07-21 15:08:07

标签: ruby exception-handling sinatra fork

我正在构建一个Sinatra API调用,它将在子进程中触发长时间运行的操作。我正在使用exception_handler gem,但不明白我在分叉过程中如何使用它。

Sinatra app:

require 'sinatra'
require 'rubygems'
require 'bundler/setup'
require 'exception_notification'

use ExceptionNotification::Rack,
  :email => {
    :email_prefix => "[Example] ",
    :sender_address => %{"notifier" <notifier@example.com>},
    :exception_recipients => %w{me@example.com},
    :delivery_method => :sendmail
  }

get '/error' do
  raise 'Bad!' # Notification gets sent
end

get '/error_async' do
  p1 = fork do
    sleep 10
    raise 'Bad! (async)' # Notification never gets sent
  end
  Process.detach(p1)
end

1 个答案:

答案 0 :(得分:1)

根据docs

了解它
get '/error_async' do

  p1 = fork do

    begin
      sleep 10
      raise 'Bad! (async)'
    rescue Exception => e
      ExceptionNotifier.notify_exception(e)
    end

  end
  Process.detach(p1)

end