/
condition_hooks.clj
77 lines (68 loc) · 2.42 KB
/
condition_hooks.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
(ns active.clojure.condition-hooks
(:require [active.clojure.condition :as c]
[clojure.main :as main]
[clojure.test :refer :all]
[clojure.stacktrace :as stack]))
(defn repl-caught
[& [e]]
(let [e (or e *e)]
(if (c/condition? e)
(c/print-condition e *err*)
(main/repl-caught e))))
;; This trick (if it is one) stolen from humane-test-output
(defonce activation-body
(delay
(defmethod report :error [m]
[m]
(with-test-out
(inc-report-counter :error)
(println "\nERROR in" (testing-vars-str m))
(when (seq *testing-contexts*) (println (testing-contexts-str)))
(when-let [message (:message m)] (println message))
(println "expected:" (pr-str (:expected m)))
(print " actual: ")
(let [actual (:actual m)]
(cond
(c/condition? actual) (c/print-condition actual *out*)
(instance? Throwable actual)
(stack/print-cause-trace actual *stack-trace-depth*)
:else (prn actual)))))))
(defn activate-clojure-test! []
@activation-body)
(defn root-cause
"Returns the initial cause of an exception or error by peeling off all of
its wrappers"
[^Throwable t]
(loop [cause t]
(if (and (instance? clojure.lang.Compiler$CompilerException cause)
(not= (.source ^clojure.lang.Compiler$CompilerException cause) "NO_SOURCE_FILE"))
(.getCause cause)) ; one level up ...
(if-let [cause (.getCause cause)]
(recur cause)
cause)))
(defn print-stack-trace-of
[^Throwable exc]
(let [st (.getStackTrace exc)]
(if-let [e (first st)]
(clojure.stacktrace/print-trace-element e)
(print "[empty stack trace]"))
(newline)
(doseq [e (rest st)]
(print " ")
(clojure.stacktrace/print-trace-element e)
(newline))))
(defn install-default-uncaught-exception-handler!
"Install an exception handler of last resort that will print a stack trace."
[]
(Thread/setDefaultUncaughtExceptionHandler
(reify Thread$UncaughtExceptionHandler
(uncaughtException [this t e0]
(let [e (root-cause e0)]
(if (c/condition? e)
(do
(c/print-condition e *err*)
(.flush ^java.io.PrintWriter *err*))
(binding [*out* *err*]
(println (.getSimpleName (class e)) (.getMessage ^Exception e))
(print-stack-trace-of e)
(.flush ^java.io.PrintWriter *err*))))))))