如何使用 Thor 在 ruby 的终端上抑制而不打印异常的回溯?
以下是我可能引发异常的方法。
这也是我正在构建的 CLI 的一种方法。
每当异常发生时,我想捕获它并在终端上打印我的自定义消息。
# variation 1
def self.validate(yaml_path)
begin
....
....
rescue
puts "Error"
end
end
# variation 2
def self.validate(yaml_path)
begin
....
....
rescue Exceptino => e
puts "Error: #{e.message}"
end
end
但回溯会打印在终端上。
如何避免回溯被打印?
± ../../bin/cf site create
ruby-1.8.7-p352
Error during processing: syntax error on line 52, col 10: ` - label: Price'
/Users/millisami/.rvm/rubies/ruby-1.8.7-p352/lib/ruby/1.8/yaml.rb:133:in `load': syntax error on line 52, col 10: ` - label: Price' (ArgumentError)
.... backtrace .....
.............
Following is my method that might raise the exception.
Its a method of the CLI too that I am building.
Whenever the exception occurs, I want to catch that and just print my custom message on the terminal.
# variation 1
def self.validate(yaml_path)
begin
....
....
rescue
puts "Error"
end
end
# variation 2
def self.validate(yaml_path)
begin
....
....
rescue Exceptino => e
puts "Error: #{e.message}"
end
end
But the backtrace gets printed on the terminal.
How to avoid the backtrace to get printed?
± ../../bin/cf site create
ruby-1.8.7-p352
Error during processing: syntax error on line 52, col 10: ` - label: Price'
/Users/millisami/.rvm/rubies/ruby-1.8.7-p352/lib/ruby/1.8/yaml.rb:133:in `load': syntax error on line 52, col 10: ` - label: Price' (ArgumentError)
.... backtrace .....
.............
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
答案是在
bin/
的可执行文件中拯救它。感谢您的建议
The answer was to rescue it on the executable file at
bin/<exe>
.Thanks for suggesting
以下代码不输出回溯。
您是否检查过堆栈中是否有另一个点,其中另一个方法正在拯救异常,输出堆栈跟踪,然后重新引发异常?
The following code doesn't output the backtrace.
Have you checked to see if there is another point in the stack where another method is rescuing the exception, outputting the stack trace and then re-raising the exception?
您不拯救异常的原因是因为
Psych::SyntaxError
不是StandardError
的后代,因此简单的rescue
不会捕获它。您需要指定Psych::SyntaxError
的后代:请注意,在我的示例中,
rescue Exception
确实捕获了它。通常,救援时您应该尽可能具体,除非您确实需要救援所有异常
。请注意,当异常是您所期望的情况时,抑制回溯是很好的选择,但如果您通常不希望出现这种情况,那么调试就会变得更加困难。The reason you're not rescuing the exception is because
Psych::SyntaxError
is not descended fromStandardError
, so a simplerescue
won't catch it. You need to specify a descendant ofPsych::SyntaxError
:Notice that in my example
rescue Exception
does catch it. You should generally be as specific as you can when rescuing unless you really need to rescue allExceptions
. Be aware that suppressing backtraces is good when the exception is something you expect, but if you don't expect it in general it makes debugging much harder.