summaryrefslogtreecommitdiff
path: root/lib/pry/exception_handler.rb
blob: 9b50fe800debb497f357ac3b67f07e4a30d03ad4 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
class Pry
  # @api private
  # @since ?.?.?
  module ExceptionHandler
    class << self
      # Will only show the first line of the backtrace.
      def handle_exception(output, exception, _pry_instance)
        if exception.is_a?(UserError) && exception.is_a?(SyntaxError)
          output.puts "SyntaxError: #{exception.message.sub(/.*syntax error, */m, '')}"
        else
          output.puts standard_error_text_for(exception)
        end
      end

      private

      def standard_error_text_for(exception)
        text = exception_text(exception)
        return text unless exception.respond_to?(:cause)

        cause = exception.cause
        while cause
          text += cause_text(cause)
          cause = cause.cause
        end

        text
      end

      def exception_text(exception)
        "#{exception.class}: #{exception.message}\n" \
        "from #{exception.backtrace.first}\n"
      end

      def cause_text(cause)
        "Caused by #{cause.class}: #{cause}\n" \
        "from #{cause.backtrace.first}\n"
      end
    end
  end
end