问题
When exiting a Rails app using raise
or fail
, how to prevent the backtrace from being displayed?
Tried using back_trace_limit
but it only seems to work for the console...?
回答1:
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
Output:
hello
Error message: ERROR!
Error backtrace: []
The strip_backtrace method here catches all errors, sets the backtrace to an empty array, and re-raises the modified exception.
来源:https://stackoverflow.com/questions/16304905/how-to-suppress-backtrace-in-rails