Sha256: 83a09b1c982649e0ae74a0c420f33e22a6d61219f3c95e7805e0d22d2f5fd92a

Contents?: true

Size: 1.2 KB

Versions: 2

Compression:

Stored size: 1.2 KB

Contents

# frozen_string_literal: true

require 'thread'

require_relative 'logger'

module Listen
  module Thread
    class << self
      # Creates a new thread with the given name.
      # Any exceptions raised by the thread will be logged with the thread name and complete backtrace.
      def new(name)
        thread_name = "listen-#{name}"

        caller_stack = caller
        ::Thread.new do
          begin
            yield
          rescue Exception => ex
            _log_exception(ex, thread_name, caller_stack)
            nil
          end
        end.tap do |thread|
          thread.name = thread_name
        end
      end

      private

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

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

Version data entries

2 entries across 2 versions & 1 rubygems

Version Path
listen-3.3.0.pre.3 lib/listen/thread.rb
listen-3.3.0.pre.2 lib/listen/thread.rb