Class: Backtrace
- Inherits:
-
Object
- Object
- Backtrace
- Defined in:
- lib/backtrace.rb
Overview
Backtrace as a string.
This class helps format Ruby exceptions with their backtraces in a clean, readable format. It can also filter backtrace lines to show only relevant information.
- Author
-
Yegor Bugayenko ([email protected])
- Copyright
-
Copyright © 2018-2025 Yegor Bugayenko
- License
-
MIT
Class Method Summary collapse
-
.exec(swallow: false, log: nil, mine: '') { ... } ⇒ Object
Executes a block and handles exceptions with formatted backtrace.
Instance Method Summary collapse
-
#initialize(exp, mine: '') ⇒ Backtrace
constructor
Creates a new Backtrace instance.
-
#to_s ⇒ String
Converts the backtrace to a formatted string.
Constructor Details
#initialize(exp, mine: '') ⇒ Backtrace
Creates a new Backtrace instance.
41 42 43 44 |
# File 'lib/backtrace.rb', line 41 def initialize(exp, mine: '') @exp = exp @mine = (mine.is_a?(Regexp) ? mine : Regexp.new(Regexp.quote(mine))) end |
Class Method Details
.exec(swallow: false, log: nil, mine: '') { ... } ⇒ Object
Executes a block and handles exceptions with formatted backtrace.
This method provides a convenient way to wrap code that might raise exceptions. It will format and display (or log) any exceptions that occur.
110 111 112 113 114 115 116 117 118 119 120 |
# File 'lib/backtrace.rb', line 110 def self.exec(swallow: false, log: nil, mine: '') yield rescue StandardError => e trace = Backtrace.new(e, mine: mine).to_s if log.nil? || !log.respond_to?(:error) puts trace else log.error(trace) end raise e unless swallow end |
Instance Method Details
#to_s ⇒ String
Converts the backtrace to a formatted string.
The output includes the exception class name, message, and a filtered backtrace. Lines are indented with tabs for readability.
63 64 65 66 67 68 69 70 71 72 73 74 75 |
# File 'lib/backtrace.rb', line 63 def to_s bt = @exp.backtrace &.reverse &.drop_while { |t| @mine.match(t).nil? } &.reverse &.join("\n\t") [ @exp.class.name, ': ', @exp., ("\n\t#{bt}" if bt) ].join end |