ruby-on-railsrubyrescue

Retrieve method that caused error using Rescue


Let's say you have the following example code block:

  def next_page(next_token)
    client.list_order_items_by_next_token(next_token)
  rescue => error
    binding.pry
  end

Without diving into the issue that this rescue is capturing all errors and how that is bad (this block has been modified) is there a way to determine the method list_order_items_by_next_token caused the issue? I know the stack trace is available but that does not feel right.


Solution

  • Just use

    error.backtrace
    

    Don't worry about performance.

    By the time you rescue the exception the cost of creating the backtrace has already occurred. The backtrace is created when the exception is raised. And it is expensive! Ruby has to create O(N) new strings whenever an exception is raised, where N is the depth of the stacktrace. Which can be 1000+ in a common Rails application. It gets even worse in a loop. And all these strings are usually never used and just clog up garbage collection. In our production system those backtrace strings are one of the major causes of performance degradation. But as I said, that cost occurs when the exception is raised, accessing the backtrace later is free of cost.