liveBook · Manning

Root-cause

As explained in Clojure: The Essential Reference

root-cause is a Clojure function that returns the innermost underlying exception in a chain of wrapped exceptions.

root-cause is a Clojure exception-handling function that unwraps an exception chain and returns its innermost underlying exception. section 22.3

Use it when nested exceptions obscure the original failure:

  • Refer to root-cause from clojure.repl before calling it. section 22.3
  • Pass the outer exception; receive the deepest underlying exception in the wrapping chain. section 22.3

Recover the original failure

(require '[clojure.repl :refer [root-cause]]) (pst (root-cause ex) 3) ;; ArithmeticException Divide by zero ;; clojure.lang.Numbers.divide (Numbers.java:158) Here, ex wraps an ExceptionInfo describing what happened, which itself wraps the original division-by-zero exception. section 22.3

(require '[clojure.repl :refer [root-cause]]) ; #1
(pst (root-cause ex) 3) ; #2

;; ArithmeticException Divide by zero
;;   clojure.lang.Numbers.divide (Numbers.java:158)
;;   clojure.lang.Numbers.divide (Numbers.java:3808)
;;   user/fn--2169 (form-init4179141376169992155.clj:3)

Inspect the compact stack trace for the innermost exception returned by root-cause. section 22.3

How Clojure: The Essential Reference covers it

How deep it goes
Defines unwrapping behavior and demonstrates nested exceptions, but does not detail edge cases or implementation internals.
Examples
Uses nested ex-info values around a divide-by-zero ArithmeticException and prints the resulting stack trace.
What you can do after
Diagnose wrapped failures by extracting and inspecting the innermost underlying exception.
How it connects
Connects exception handling with ex-info and stack traces.

Related concepts

This explainer was generated by Manning's knowledge graph from the text of Clojure: The Essential Reference. The section links point to the parts of the book it draws on.