我想给
STDOUT
或 STDERR
写一条干净、简单的错误消息给用户,没有(冗长的)回溯。我目前正在使用 raise
编写错误消息并退出,如这个简化示例所示:
#!/usr/bin/env ruby
def bar
raise "this needs to be clean, no backtrace"
end
bar
写给
STDERR
:
/Users/foo/test/test1.rb:4:in `bar': this needs to be clean, no backtrace (RuntimeError)
from /Users/foo/test/test1.rb:7:in `<main>'
我只想写这部分:
this needs to be clean, no backtrace
现实生活中的例子有一个更详细的回溯,以及多个
raise
语句来处理不同的故障模式和自定义消息。
我知道我可以做这样的事情(为了干净
STDOUT
),但我想避免重复代码:
puts "this needs to be clean, no backtrace"
raise "this needs to be clean, no backtrace"
相关:
raise
- 或类似的东西 - 立即终止程序,以及 (b) 只打印错误消息,而不是完整的堆栈跟踪或回溯,这让我们的用户感到困惑。warn
(或直接写到$stderr
),也许连同exit
:
def bar
warn "this needs to be clean, no backtrace"
exit(false)
end
bar
at_exit
处理程序来检查异常类,打印其消息并使标准输出静音以抑制回溯。像这样的东西:
class SimpleError < StandardError ; end
at_exit do
if $!.is_a?(SimpleError)
$stderr.puts($!.message)
$stderr.reopen(IO::NULL)
end
end
def bar
raise SimpleError, "this needs to be clean, no backtrace"
end
bar
使这种错误处理成为可选的可能是个好主意。
您是否正在尝试重写 Ruby 将未捕获异常写入 STDERR 的方式?我不知道那是否容易完成(或可取)。
不过,您可以在自定义异常中覆盖回溯,这不会影响任何其他内容。
class ExceptionWithoutBacktrace < StandardError
def backtrace
[]
end
end
raise ExceptionWithoutBacktrace, "This should be printed clean"