/
exception.clj
764 lines (638 loc) · 29.7 KB
/
exception.clj
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
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
(ns io.aviso.exception
"Format and present exceptions in a pretty (structured, formatted) way."
(:require [clojure
[pprint :as pp]
[set :as set]
[string :as str]]
[io.aviso
[ansi :as ansi]
[columns :as c]])
(:import
(java.lang StringBuilder StackTraceElement)
(clojure.lang Compiler ExceptionInfo Named)
(java.util.regex Pattern)))
(def default-fonts
"A default set of fonts for different elements in the formatted exception report."
{:exception ansi/bold-red-font
:reset ansi/reset-font
:message ansi/italic-font
:property ansi/bold-font
:source ansi/green-font
:app-frame ansi/bold-yellow-font
:function-name ansi/bold-yellow-font
:clojure-frame ansi/yellow-font
:java-frame ansi/white-font
:omitted-frame ansi/white-font})
(def ^:dynamic *app-frame-names*
"Set of filters (belong to your applications) to create more visual clarity."
nil)
(def ^:dynamic *fonts*
"Current set of fonts used in exception formatting"
(when-not (System/getenv "DISABLE_DEFAULT_PRETTY_FONTS")
default-fonts))
(def ^{:dynamic true
:added "0.1.15"}
*traditional*
"If bound to true, then exceptions will be formatted the traditional way (the only option prior to 0.1.15)."
false)
(defn ^:private length [^String s] (.length s))
(defn ^:private strip-prefix
[^String prefix ^String input]
(let [prefix-len (.length prefix)]
(if (and (.startsWith input prefix)
(< prefix-len (.length input)))
(.substring input prefix-len)
input)))
(def ^:private current-dir-prefix
"Convert the current directory (via property 'user.dir') into a prefix to be omitted from file names."
(delay (str (System/getProperty "user.dir") "/")))
(defn ^:private ?reverse
[reverse? coll]
(if reverse?
(reverse coll)
coll))
;;; Obviously, this is making use of some internals of Clojure that
;;; could change at any time.
(def ^:private clojure->java
(->> (Compiler/CHAR_MAP)
set/map-invert
(sort-by #(-> % first length))
reverse))
(defn ^:private match-mangled
[^String s i]
(->> clojure->java
(filter (fn [[k _]] (.regionMatches s i k 0 (length k))))
;; Return the matching sequence and its single character replacement
first))
(defn demangle
"De-mangle a Java name back to a Clojure name by converting mangled sequences, such as \"_QMARK_\"
back into simple characters."
[^String s]
(let [in-length (.length s)
result (StringBuilder. in-length)]
(loop [i 0]
(cond
(>= i in-length) (.toString result)
(= \_ (.charAt s i)) (let [[match replacement] (match-mangled s i)]
(.append result replacement)
(recur (long (+ i (length match)))))
:else (do
(.append result (.charAt s i))
(recur (inc i)))))))
(defn ^:private match-keys
"Apply the function f to all values in the map; where the result is truthy, add the key to the result."
[m f]
;; (seq m) is necessary because the source is via (bean), which returns an odd implementation of map
(reduce (fn [result [k v]] (if (f v) (conj result k) result)) [] (seq m)))
(def ^{:added "0.1.18"
:dynamic true}
*default-frame-rules*
"The set of rules that forms the basis for [[*default-frame-filter*]], as a vector or vectors.
Each rule is three values:
* A function that extracts the value from the stack frame map (typically, this is a keyword such
as :package or :name). The value is converted to a string.
* A string or regexp used for matching.
* A resulting frame visibility (:hide, :omit, :terminate, or :show).
The default rules:
* omit everything in clojure.lang and java.lang.reflect.
* hide everything in sun.reflect
* terminate at speclj.* or clojure.main/repl/read-eval-print
"
[[:package "clojure.lang" :omit]
[:package #"sun\.reflect.*" :hide]
[:package "java.lang.reflect" :omit]
[:name #"speclj\..*" :terminate]
[:name #"clojure\.main/repl/read-eval-print.*" :terminate]])
(defn ^:private apply-rule
[frame [f match visibility :as rule]]
(let [value (str (f frame))]
(cond
(string? match)
(if (= match value) visibility)
(instance? Pattern match)
(if (re-matches match value) visibility)
:else
(throw (ex-info "Unexpected match type in rule."
{:rule rule})))))
(defn *default-frame-filter*
"Default stack frame filter used when printing REPL exceptions. This will omit frames in the `clojure.lang`
and `java.lang.reflect` package, hide frames in the `sun.reflect` package,
and terminates the stack trace at the read-eval-print loop frame."
{:added "0.1.16"
:dynamic true}
[frame]
(-> (keep #(apply-rule frame %) *default-frame-rules*)
first
(or :show)))
(defn ^:private convert-to-clojure
[class-name method-name]
(let [[namespace-name & raw-function-ids] (str/split class-name #"\$")
;; Clojure adds __1234 unique ids to the ends of things, remove those.
function-ids (map #(str/replace % #"__\d+" "") raw-function-ids)
;; In a degenerate case, a protocol method could be called "invoke" or "doInvoke"; we're ignoring
;; that possibility here and assuming it's the IFn.invoke(), doInvoke() or
;; the invokeStatic method introduced with direct linking in Clojure 1.8.
all-ids (if (#{"invoke" "doInvoke" "invokeStatic" "invokePrim"} method-name)
function-ids
(-> function-ids vec (conj method-name)))]
;; The assumption is that no real namespace or function name will contain underscores (the underscores
;; are name-mangled dashes).
(->>
(cons namespace-name all-ids)
(map demangle))))
(defn ^:private extension
[^String file-name]
(let [x (.lastIndexOf file-name ".")]
(when (<= 0 x)
(subs file-name (inc x)))))
(def ^:private clojure-extensions
#{"clj" "cljc"})
(defn ^:private expand-stack-trace-element
[file-name-prefix ^StackTraceElement element]
(let [class-name (.getClassName element)
method-name (.getMethodName element)
dotx (.lastIndexOf class-name ".")
file-name (or (.getFileName element) "")
is-clojure? (->> file-name extension (contains? clojure-extensions))
names (if is-clojure? (convert-to-clojure class-name method-name) [])
name (str/join "/" names)
; This pattern comes from somewhere inside nREPL, I believe
[file line] (if (re-matches #"form-init\d+\.clj" file-name)
["REPL Input"]
[(strip-prefix file-name-prefix file-name)
(-> element .getLineNumber)])]
{:file file
; line will sometimes be nil
:line (if (and line
(pos? line))
line)
:class class-name
:package (if (pos? dotx) (.substring class-name 0 dotx))
:is-clojure? is-clojure?
:simple-class (if (pos? dotx)
(.substring class-name (inc dotx))
class-name)
:method method-name
;; Used to calculate column width
:name name
;; Used to present compound Clojure name with last term highlighted
:names names}))
(def ^:private empty-stack-trace-warning
"Stack trace of root exception is empty; this is likely due to a JVM optimization that can be disabled with -XX:-OmitStackTraceInFastThrow.")
(defn ^:private apply-frame-filter
[frame-filter frames]
(if (nil? frame-filter)
frames
(loop [result (transient [])
[frame & more-frames] frames
omitting false]
(case (if frame (frame-filter frame) :terminate)
:terminate
(persistent! result)
:show
(recur (conj! result frame)
more-frames
false)
:hide
(recur result more-frames omitting)
:omit
(if omitting
(recur result more-frames true)
(recur (conj! result (assoc frame :omitted true))
more-frames
true))))))
(defn ^:private remove-direct-link-frames
"With Clojure 1.8, in code (such as clojure.core) that is direct linked,
you'll often see an invokeStatic() and/or invokePrim() frame invoked from an invoke() frame
of the same class (the class being a compiled function). That ends up looking
like a two-frame repeat, which is not accurate.
This function filters out the .invoke frames so that a single Clojure
function call is represented in the output as a single stack frame."
[elements]
(loop [filtered (transient [])
prev-frame nil
remaining elements]
(if (empty? remaining)
(persistent! filtered)
(let [[this-frame & rest] remaining]
(if (and prev-frame
(:is-clojure? prev-frame)
(:is-clojure? this-frame)
(= (:class prev-frame) (:class this-frame))
(= "invokeStatic" (:method prev-frame))
(contains? #{"invoke" "invokePrim"} (:method this-frame)))
(recur filtered this-frame rest)
(recur (conj! filtered this-frame)
this-frame
rest))))))
(defn ^:private is-repeat?
[left-frame right-frame]
(and (= (:formatted-name left-frame)
(:formatted-name right-frame))
(= (:line left-frame)
(:line right-frame))))
(defn ^:private repeating-frame-reducer
[output-frames frame]
(let [output-count (count output-frames)
last-output-index (dec output-count)]
(cond
(zero? output-count)
(conj output-frames frame)
(is-repeat? (output-frames last-output-index) frame)
(update-in output-frames [last-output-index :repeats]
(fnil inc 1))
:else
(conj output-frames frame))))
(defn ^:private format-repeats
[{:keys [repeats]}]
(if repeats
(format " (repeats %,d times)" repeats)))
(defn expand-stack-trace
"Extracts the stack trace for an exception and returns a seq of expanded stack frame maps:
:file String
: file name
:line Integer
: line number as an integer, or nil
:class String
: fully qualified Java class name
:package String
: Java package name, or nil for root package
:simple-class String
: simple name of Java class (without package prefix)
:method String
: Java method name
:is-clojure?
: true if this represents a Clojure function call, rather than a Java
method invocation.
:name String
: Fully qualified Clojure name (demangled from the Java class name), or the empty string for non-Clojure stack frames
:names seq of String
: Clojure name split at slashes (empty for non-Clojure stack frames)"
[^Throwable exception]
(let [elements (map (partial expand-stack-trace-element @current-dir-prefix) (.getStackTrace exception))]
(when (empty? elements)
(binding [*out* *err*]
(println empty-stack-trace-warning)
(flush)))
elements))
(defn ^:private clj-frame-font
"Returns the font to use for a clojure frame.
When provided a frame matching *app-frame-names*, returns :app-frame, otherwise :clojure-frame
"
[frame]
(-> (keep #(apply-rule frame [:name % :app-frame]) *app-frame-names*)
first
(or :clojure-frame)))
(defn ^:private preformat-stack-frame
[frame]
(cond
(:omitted frame)
(assoc frame :formatted-name (str (:omitted-frame *fonts*) "..." (:reset *fonts*))
:file ""
:line nil)
;; When :names is empty, it's a Java (not Clojure) frame
(-> frame :names empty?)
(let [full-name (str (:class frame) "." (:method frame))
formatted-name (str (:java-frame *fonts*) full-name (:reset *fonts*))]
(assoc frame
:formatted-name formatted-name))
:else
(let [names (:names frame)
formatted-name (str
(get *fonts* (clj-frame-font frame))
(->> names drop-last (str/join "/"))
"/"
(:function-name *fonts*) (last names) (:reset *fonts*))]
(assoc frame :formatted-name formatted-name))))
(defn ^:private transform-stack-trace-elements
"Converts a seq of StackTraceElements into a seq of stack trace maps."
[elements options]
(let [frame-filter (:filter options *default-frame-filter*)
frame-limit (:frame-limit options)
elements' (->> elements
remove-direct-link-frames
(apply-frame-filter frame-filter)
(map preformat-stack-frame)
(reduce repeating-frame-reducer []))]
(if frame-limit
(take frame-limit elements')
elements')))
(defn ^:private extract-stack-trace
[exception options]
(transform-stack-trace-elements (expand-stack-trace exception) options))
(defn ^:private is-throwable? [v]
(.isInstance Throwable v))
(defn ^:private wrap-exception
[^Throwable exception properties options]
(let [throwable-property-keys (match-keys properties is-throwable?)
nested-exception (or (->> (select-keys properties throwable-property-keys)
vals
(remove nil?)
;; Avoid infinite loop!
(remove #(= % exception))
first)
(.getCause exception))
stack-trace (when-not nested-exception
(extract-stack-trace exception options))]
[{:class-name (-> exception .getClass .getName)
:message (.getMessage exception)
;; Don't ever want to include throwables since they will wreck the output format.
;; Would only expect a single throwable (either an explicit property, or as the cause)
;; per exception.
:properties (apply dissoc properties throwable-property-keys)
:stack-trace stack-trace}
nested-exception]))
(defn ^:private expand-exception
[^Throwable exception options]
(if (instance? ExceptionInfo exception)
(wrap-exception exception (ex-data exception) options)
(let [properties (bean exception)
;; Ignore basic properties of Throwable, any nil properties, and any properties
;; that are themselves Throwables
discarded-keys (concat [:suppressed :message :localizedMessage :class :stackTrace :cause]
(match-keys properties nil?)
(match-keys properties is-throwable?))
retained-properties (apply dissoc properties discarded-keys)]
(wrap-exception exception retained-properties options))))
(defn analyze-exception
"Converts an exception into a seq of maps representing nested exceptions.
The order reflects exception nesting; first exception is the most recently
thrown, last is the deepest, or root, exception ... the initial exception
thrown in a chain of nested exceptions.
The options map is as defined by [[write-exception]].
Each exception map contains:
:class-name String
: name of the Java class for the exception
:message String
: value of the exception's message property (possibly nil)
:properties Map
: map of properties to (optionally) present in the exception report
:stack-trace Vector
: stack trace element maps, or nil.
Only present in the root exception.
The :properties map does not include any properties that are assignable to type Throwable.
The first property that is assignable to type Throwable (not necessarily the rootCause property)
will be used as the nested exception (for the next map in the sequence)."
[^Throwable e options]
(loop [result []
current e]
(let [[expanded nested] (expand-exception current options)
result' (conj result expanded)]
(if nested
(recur result' nested)
result'))))
(defn ^:private update-keys [m f]
"Builds a map where f has been applied to each key in m."
(reduce-kv (fn [m k v]
(assoc m (f k) v))
{}
m))
(defn ^:private write-stack-trace
[stack-trace modern?]
(c/write-rows [:formatted-name
" "
(:source *fonts*)
#(if (:line %)
(str (:file %) ":")
(:file %))
" "
#(-> % :line str)
[format-repeats :none]
(:reset *fonts*)]
(?reverse modern? stack-trace)))
(defmulti exception-dispatch
"The pretty print dispatch function used when formatting exception output (specifically, when
printing the properties of an exception). Normally, this is the same as the simple-dispatch
(in clojure.pprint) but can be extended for specific cases:
(import com.stuartsierra.component.SystemMap)
(defmethod exception-dispatch SystemMap [system-map] (print \"#<SystemMap>\"))
This ensures that the SystemMap record, wherever it appears in the exception output,
is represented as the string `#<SystemMap>`; normally it would print as a deeply nested
set of maps.
See the [[io.aviso.component]] namespace for more complete example.
This same approach can be adapted to any class or type whose structure is problematic
for presenting in the exception output, whether for size and complexity reasons, or due to
security concerns."
class)
(defmethod exception-dispatch Object
[object]
(pp/simple-dispatch object))
(defmethod exception-dispatch nil
[_]
(pp/simple-dispatch nil))
(defn ^:private format-property-value
[value]
(pp/write value :stream nil :length (or *print-length* 10) :dispatch exception-dispatch))
(defn ^:private qualified-name [x]
(if (instance? Named x)
(let [x-ns (namespace x)
x-name (name x)]
(if x-ns
(str x-ns "/" x-name)
x-name))
x))
(defn write-exception*
"Contains the main logic for [[write-exception]], which simply expands
the exception (via [[analyze-exception]]) before invoking this function.
This code was extracted so as to support [[parse-exception]]."
{:added "0.1.21"}
[exception-stack options]
(let [{show-properties? :properties
:or {show-properties? true}} options
exception-font (:exception *fonts*)
message-font (:message *fonts*)
property-font (:property *fonts*)
reset-font (:reset *fonts* "")
modern? (not *traditional*)
exception-formatter (c/format-columns [:right (c/max-value-length exception-stack :class-name)]
": "
:none)
write-exception-stack #(doseq [e (?reverse modern? exception-stack)]
(let [{:keys [class-name message]} e]
(exception-formatter (str exception-font class-name reset-font)
(str message-font message reset-font))
(when show-properties?
(let [properties (update-keys (:properties e) qualified-name)
prop-keys-sorted (cond-> (keys properties)
(not (sorted? (:properties e)))
(sort))
;; Allow for the width of the exception class name, and some extra
;; indentation.
property-formatter (c/format-columns " "
[:right (c/max-length prop-keys-sorted)]
": "
:none)]
(doseq [k prop-keys-sorted]
(property-formatter (str property-font k reset-font)
(-> properties (get k) format-property-value)))))))
root-stack-trace (-> exception-stack last :stack-trace)]
(if *traditional*
(write-exception-stack))
(write-stack-trace root-stack-trace modern?)
(if modern?
(write-exception-stack))))
(defn write-exception
"Writes a formatted version of the exception to *out*. By default, includes
the stack trace, with no frame limit.
The options map may have the following keys:
:filter
: The stack frame filter, which defaults to [[*default-stack-frame-filter*]].
:properties
: If true (the default) then properties of exceptions will be output.
:frame-limit
: If non-nil, the number of stack frames to keep when outputing the stack trace
of the deepest exception.
Output may be traditional or modern, as controlled by [[*traditional*]].
Traditional is the typical output order for Java: the stack of exceptions comes first (outermost to
innermost) followed by the stack trace of the innermost exception, with the frames
in deepest to shallowest order.
Modern output is more readable; the stack trace comes first and is reversed: shallowest frame to deepest.
Then the exception stack is output, from the root exception to the outermost exception.
The modern output order is more readable, as it puts the most useful information together at the bottom, so that
it is not necessary to scroll back to see, for example, where the exception occurred.
The default is modern.
The stack frame filter is passed the map detailing each stack frame
in the stack trace, must return one of the following values:
:show
: is the normal state; display the stack frame.
:hide
: prevents the frame from being displayed, as if it never existed.
:omit
: replaces the frame with a \"...\" placeholder; multiple consecutive :omits will be collapsed to a single line.
Use :omit for \"uninteresting\" stack frames.
:terminate
: hides the frame AND all later frames.
The default filter is [[*default-frame-filter*]]. An explicit filter of nil will display all stack frames.
Repeating lines are collapsed to a single line, with a repeat count. Typically, this is the result of
an endless loop that terminates with a StackOverflowException.
When set, the frame limit is the number of stack frames to display; if non-nil, then some of the outermost
stack frames may be omitted. It may be set to 0 to omit the stack trace entirely (but still display
the exception stack). The frame limit is applied after the frame filter (which may hide or omit frames) and
after repeating stack frames have been identified and coallesced ... :frame-limit is really the number
of _output_ lines to present.
Properties of exceptions will be output using Clojure's pretty-printer, honoring all of the normal vars used
to configure pretty-printing; however, if `*print-length*` is left as its default (nil), the print length will be set to 10.
This is to ensure that infinite lists do not cause endless output or other exceptions.
The `*fonts*` var contains ANSI definitions for how fonts are displayed; bind it to nil to remove ANSI formatting entirely.
It can be also initialized to nil instead of the default set of fonts by setting environment variable DISABLE_DEFAULT_PRETTY_FONTS
to any value."
([exception]
(write-exception exception nil))
([exception options]
(write-exception* (analyze-exception exception options) options)))
(defn format-exception
"Formats an exception as a multi-line string using [[write-exception]]."
([exception]
(format-exception exception nil))
([exception options]
(with-out-str (write-exception exception options))))
(defn ^:private assemble-final-stack [exceptions stack-trace stack-trace-batch options]
(let [stack-trace' (-> (map (partial expand-stack-trace-element @current-dir-prefix)
(into stack-trace-batch stack-trace))
(transform-stack-trace-elements options))
x (-> exceptions count dec)]
(assoc-in exceptions [x :stack-trace] stack-trace')))
(def ^:private re-exception-start
"The start of an exception, possibly the outermost exception."
#"(Caused by: )?(\w+(\.\w+)*): (.*)"
; Group 2 - exception name
; Group 4 - exception message
)
(def ^:private re-stack-frame
;; Sometimes the file name and line number are replaced with "Unknown source"
#"\s+at ([a-zA-Z_.$\d<>]+)\(((.+):(\d+))?.*\).*"
; Group 1 - class and method name
; Group 3 - file name (or nil)
; Group 4 - line number (or nil)
)
(defn ^:private add-message-text
[exceptions line]
(let [x (-> exceptions count dec)]
(update-in exceptions [x :message]
str \newline line)))
(defn ^:private add-to-batch [stack-trace-batch ^String class-and-method ^String file-name ^String line-number]
(try
(let [x (.lastIndexOf class-and-method ".")
class-name (subs class-and-method 0 x)
method-name (subs class-and-method (inc x))
element (StackTraceElement. class-name method-name file-name (if line-number
(Integer/parseInt line-number)
-1))]
(conj stack-trace-batch element))
(catch Throwable t
(throw (ex-info "Unable to create StackTraceElement."
{:class-and-method class-and-method
:file-name file-name
:line-number line-number}
t)))))
(defn parse-exception
"Given a chunk of text for an exception report (as with `.printStackTrace`), attempts to
piece together the same information provided by [[analyze-exception]]. The result
is ready to pass to [[write-exception*]].
This code does not attempt to recreate properties associated with the exceptions; in most
exception's cases, this is not necessarily written to the output. For clojure.lang.ExceptionInfo,
it is hard to distinguish the message text from the printed exception map.
The options are used when processing the stack trace and may include the :filter and :frame-limit keys.
Returns a sequence of exception maps; the final map will include the :stack-trace key (a vector
of stack trace element maps). The exception maps are ordered outermost to innermost (that final map
is the root exception).
This should be considered experimental code; there are many cases where it may not work properly.
It will work quite poorly with exceptions whose message incorporates a nested exception's
.printStackTrace output. This happens too often with JDBC exceptions, for example."
{:added "0.1.21"}
[exception-text options]
(loop [state :start
lines (str/split-lines exception-text)
exceptions []
stack-trace []
stack-trace-batch []]
(if (empty? lines)
(assemble-final-stack exceptions stack-trace stack-trace-batch options)
(let [[line & more-lines] lines]
(condp = state
:start
(let [[_ _ exception-class-name _ exception-message] (re-matches re-exception-start line)]
(when-not exception-class-name
(throw (ex-info "Unable to parse start of exception."
{:line line
:exception-text exception-text})))
;; The exception message may span a couple of lines, so check for that before absorbing
;; more stack trace
(recur :exception-message
more-lines
(conj exceptions {:class-name exception-class-name
:message exception-message})
stack-trace
stack-trace-batch))
:exception-message
(if (re-matches re-stack-frame line)
(recur :stack-frame lines exceptions stack-trace stack-trace-batch)
(recur :exception-message
more-lines
(add-message-text exceptions line)
stack-trace
stack-trace-batch))
:stack-frame
(let [[_ class-and-method _ file-name line-number] (re-matches re-stack-frame line)]
(if class-and-method
(recur :stack-frame
more-lines
exceptions
stack-trace
(add-to-batch stack-trace-batch class-and-method file-name line-number))
(recur :skip-more-line
lines
exceptions
;; With the weird ordering of the JDK, what we see is
;; a batch of entries that actually precede frames from earlier
;; in the output (because JDK tries to present the exceptions outside in).
;; This inner exception and its abbreviated stack trace represents
;; progress downward from the previously output exception.
(into stack-trace-batch stack-trace)
[])))
:skip-more-line
(if (re-matches #"\s+\.\.\. \d+ (more|common frames omitted)" line)
(recur :start more-lines
exceptions stack-trace stack-trace-batch)
(recur :start lines
exceptions stack-trace stack-trace-batch)))))))