如何在 Rails 中抑制回溯? [英] How to suppress backtrace in Rails?
本文介绍了如何在 Rails 中抑制回溯?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
当使用 raise
或 fail
退出 Rails 应用时,如何防止显示回溯?
When exiting a Rails app using raise
or fail
, how to prevent the backtrace from being displayed?
尝试使用 back_trace_limit
但它似乎只适用于控制台......?
Tried using back_trace_limit
but it only seems to work for the console...?
推荐答案
通过使用其 set_backtrace
方法,您可以完全控制随异常实例返回的回溯.例如:
You have total control over the backtrace returned with an exception instance by using its set_backtrace
method. For example:
def strip_backtrace
yield
rescue => err
err.set_backtrace([])
raise err
end
begin
strip_backtrace do
puts 'hello'
raise 'ERROR!'
end
rescue => err
puts "Error message: #{err.message}"
puts "Error backtrace: #{err.backtrace}"
end
输出:
hello
Error message: ERROR!
Error backtrace: []
这里的 strip_backtrace 方法捕获所有错误,将回溯设置为空数组,并重新引发修改后的异常.
The strip_backtrace method here catches all errors, sets the backtrace to an empty array, and re-raises the modified exception.
这篇关于如何在 Rails 中抑制回溯?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文