【问题标题】:Handling exceptions in forked process处理分叉进程中的异常
【发布时间】:2016-11-25 06:18:33
【问题描述】:

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

Sinatra 应用程序:

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

【问题讨论】:

    标签: ruby exception-handling sinatra fork


    【解决方案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
    

    【讨论】:

    • 哇,如果您需要显式编写ExceptionNotifier.notify_exception 来发送通知,那么该gem 基本上是无用的。像这样的 gem 的真正好处是即使您不知道您的生产 Sinatra/Rails 应用程序在哪里抛出异常,因为您没有预料到它也会收到通知(如果您这样做了,那么您会有begin/rescue)。
    • @Mike 您只是将正在替换到后台进程的代码包装起来——我认为这实际上是有道理的。
    • 没错,你可以为新线程中的所有代码做一个包罗万象的工作,看起来有点便宜,但它可以完成工作。
    猜你喜欢
    • 2023-04-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-04-24
    • 2016-03-06
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多