module Listen::Thread

Experimental RBS support (using type sampling data from the type_fusion project).

# sig/listen/thread.rbs

module Listen::Thread
  def rescue_and_log: (String method_name, *Array[] args, caller_stack: Array[String]) -> nil
end

def _exception_with_causes(exception)

def _exception_with_causes(exception)
  result = +"#{exception.class}: #{exception}"
  if exception.cause
    result << "\n"
    result << "--- Caused by: ---\n"
    result << _exception_with_causes(exception.cause)
  end
  result
end

def _log_exception(exception, thread_name, caller_stack: nil)

def _log_exception(exception, thread_name, caller_stack: nil)
  complete_backtrace = if caller_stack
    [*exception.backtrace, "--- Thread.new ---", *caller_stack]
  else
    exception.backtrace
  end
  message = "Exception rescued in #{thread_name}:\n#{_exception_with_causes(exception)}\n#{complete_backtrace * "\n"}"
  Listen.logger.error(message)
end

def new(name, &block)

rubocop:disable Style/MultilineBlockChain
Any exceptions raised by the thread will be logged with the thread name and complete backtrace.
Creates a new thread with the given name.
def new(name, &block)
  thread_name = "listen-#{name}"
  caller_stack = caller
  ::Thread.new do
    rescue_and_log(thread_name, caller_stack: caller_stack, &block)
  end.tap do |thread|
    thread.name = thread_name
  end
end

def rescue_and_log(method_name, *args, caller_stack: nil)

Experimental RBS support (using type sampling data from the type_fusion project).

def rescue_and_log: (String method_name, * args, caller_stack: String | String | String) -> nil

This signature was generated using 1 sample from 1 application.

def rescue_and_log(method_name, *args, caller_stack: nil)
  yield(*args)
rescue => exception
  _log_exception(exception, method_name, caller_stack: caller_stack)
end