[英]Using Ruby Global Variable for Exception $! on rails
I'm trying to access the last exception_message from my rails app by using the ruby global variable $!, but it is coming back at nil despite multiple exceptions having occurred before the variable being called. 我正在尝试使用ruby全局变量$!从我的rails应用程序访问最后一个exception_message,但是尽管在调用该变量之前发生了多个异常,但是它返回nil。 Does this not work in rails?
这不适用于滑轨吗? Is there another way to access the last exception that was raised in the application?
还有另一种方法来访问应用程序中引发的最后一个异常吗?
I'm not sure why $!
我不确定为什么
$!
always returns nil
. 总是返回
nil
。 As I wrote in the comment above, 0 / 0 rescue $!
正如我在上面的评论中所写,
0 / 0 rescue $!
works but I can't seem to get it to work in any other context. 可以,但是我似乎无法在其他任何环境下使用它。
One way you can access the exception in a Ruby program is by using =>
after rescue
like so: 可以在Ruby程序中访问异常的一种方法是在
rescue
后使用=>
,如下所示:
[24] pry(main)> begin
[24] pry(main)* undefined_variable
[24] pry(main)* rescue => e
[24] pry(main)* puts e
[24] pry(main)* end
undefined local variable or method `undefined_variable' for main:Object
=> nil
It turns out that $! 原来是$! isn't all that global.
还不是全球性的。 It just works in the call stack of the exception - which I guess makes sense.
它只在异常的调用堆栈中起作用-我想这很有意义。
https://www.honeybadger.io/blog/working-with-ruby-exceptions-outside-of-the-rescue-block/ https://www.honeybadger.io/blog/working-with-ruby-exceptions-outside-of-the-rescue-block/
"This means that $! is pretty useless inside of a shell like IRB. Often in IRB, I'll run a method and get an exception. Sometimes I'd like to get ahold of that exception object. But $! doesn't work for this." “这意味着$!在像IRB这样的shell中几乎是无用的。通常在IRB中,我会运行一个方法并获得一个异常。有时我想获得该异常对象。但是$!却没有为此工作。”
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.