Class: Backtrace

Inherits:
Object
  • Object
show all
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

Examples:

Basic usage

begin
  raise "Something went wrong"
rescue => e
  puts Backtrace.new(e)
end

Using with a filter

begin
  raise "Error in my code"
rescue => e
  puts Backtrace.new(e, mine: 'myapp')
end

Class Method Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(exp, mine: '') ⇒ Backtrace

Creates a new Backtrace instance.

Examples:

With a string pattern

Backtrace.new(exception, mine: 'myapp')

With a regular expression

Backtrace.new(exception, mine: /lib\/myapp/)

Parameters:

  • exp (Exception)

    The exception to format

  • mine (String, Regexp) (defaults to: '')

    Pattern to match against backtrace lines. When matched, backtrace will stop printing at that line.



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.

Examples:

Basic usage

Backtrace.exec do
  risky_operation
end

Swallow exceptions

Backtrace.exec(swallow: true) do
  optional_operation
end

With logging

logger = Logger.new(STDOUT)
Backtrace.exec(log: logger) do
  database_operation
end

With filtering

Backtrace.exec(mine: 'myapp', swallow: true) do
  complex_operation
end

Parameters:

  • swallow (Boolean) (defaults to: false)

    Whether to swallow the exception (default: false)

  • log (Object) (defaults to: nil)

    Logger object that responds to #error (optional)

  • mine (String, Regexp) (defaults to: '')

    Pattern to filter backtrace lines

Yields:

  • The block of code to execute

Raises:

  • (StandardError)

    Re-raises the exception unless swallow is true



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_sString

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.

Examples:

begin
  1 / 0
rescue => e
  bt = Backtrace.new(e)
  puts bt.to_s
  # => "ZeroDivisionError: divided by 0
  #     \t/path/to/file.rb:10:in `/'
  #     \t/path/to/file.rb:20:in `calculate'"
end

Returns:

  • (String)

    Formatted backtrace string



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.message,
    ("\n\t#{bt}" if bt)
  ].join
end