簡體   English   中英

救援塊未捕獲引發的錯誤

[英]Raised error is not caught by rescue block

使用動作郵件發送電子郵件時,我們遇到了生產問題。

NameError
undefined local variable or method `to_ary' for #<Mail::Part:0x0000000008e0c998>
Did you mean?  to_addrs

錯誤看起來完全是隨機的,並且行為方式與https://yehudakatz.com/2010/01/02/the-craziest-fing-bug-ive-ever-seen/

我想做的是猴子修補missing_method以使其起作用。 所以我創建了一些測試,包括

let(:part) { Mail::Part.new }

it 'returns self' do
   allow_any_instance_of(Mail::Message).to receive(:method_missing).and_raise(NameError, 'error part')
   expect([part].flatten).to eq [part]
end

並創造了猴子補丁

require 'mail'

module Mail
  class Part < Message
    # monkey patched due to same behaviour like
    # https://yehudakatz.com/2010/01/02/the-craziest-fing-bug-ive-ever-seen/v
    def method_missing(name, *args, &block)
      begin
        super
        pp :hello
      rescue NameError => e
        return [self] if name.try(:to_sym) == :to_ary
        raise e
      end
    end
  end
end

此測試的目的是Array#flatten在其內容上調用to_ary Mail::Part#method_missing通常沒有定義,但是我創建了一個來處理Mail::Message#method_missing可能出現的NameError並返回正確的值。

問題是,調用了Mail::Part#method_missing ,調用了super並引發NameError ,但是搶救無效。 pp :hello由於出現錯誤而被跳過。

所以測試最終以

NameError: error part

  0) Mail::Part call flatten with NameError returns self
     Failure/Error: expect([part].flatten).to eq [part]

     NameError:
       error part
     # ./spec/lib/core_ext/mail/part_spec.rb:13:in `flatten'
     # ./spec/lib/core_ext/mail/part_spec.rb:13:in `block (4 levels) in <top (required)>'
     # ./spec/active_record_spec_helper.rb:19:in `block (2 levels) in <top (required)>'

另一個問題是,當我嘗試時,測試最終以無限遞歸結束

def method_missing(name, *args, &block)
  return [self]
end

與相同

def method_missing(name, *args, &block)
   begin
      raises_name_error
   rescue NameError => e
      return [self] if name.try(:to_sym) == :to_ary
      raise e
   end
end

def raises_name_error
   raise NameError, 'error part'
end

但是在這種情況下,急救塊將處理NameError

有解決方案的主意嗎?

解決者

module Mail
  class Part < Message
    def to_ary
      []
    end
  end
end

我最初的解決方案嘗試不過分。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM