4

如何使从bar最后一行重新引发的异常看起来像是来自那里,而不是来自块?我想bar在回溯中看到。

begin
  raise "foo"
rescue => e # yeah, i know
  $e = e # oh boy, globals
end

sleep 1 # again, i know

def bar
  raise $e
end

bar # => test.rb:2:in `<main>': foo (RuntimeError)

编辑:

当前的回溯是

test.rb:2:in `<main>': foo (RuntimeError)

我想要的是(或类似的东西)

test.rb:10:in `bar': foo (RuntimeError)
from test.rb:13:in `<main>'
4

2 回答 2

1

我不确定这是否是正确的答案。但我决定试一试:-)

begin
  raise "foo"
rescue => e
   $e = e
end

sleep 1 

def bar    
  raise $e.class, "bar"
end

bar #=> test.rb:10:in `bar': bar (RuntimeError)
    from test.rb:13:in `<main>'

第二次尝试

begin
  ...
end

sleep 1 

def bar  
  $e.set_backtrace(["bar"])    
  raise $e
end

bar #=> bar: foo (RuntimeError)
于 2013-09-16T18:43:23.717 回答
1

我不确定这是否是您想要的,但您可以尝试:

begin
  raise "foo"
rescue => e
  $e = e
end

sleep 1 

def get_full_stack
  caller
end

def bar
  exception = $e.dup
  exception.set_backtrace get_full_stack   
  raise exception
end
于 2013-09-16T18:53:26.943 回答