我应该如何在clojure中编码异常?

时间:2018-03-23 16:34:13

标签: clojure compojure-api sumologic

我希望能够对json编码异常对象。我正在将我的日志推送到sumologic,并且希望能够推送json编码的异常,以便我可以在sumo中解析和过滤这些日志。

但是,我无法对该异常进行json编码并收到此错误:

Cannot JSON encode object of class: class java.lang.Class: class clojure.lang.ExceptionInfo

这是我的compojure-api异常处理程序:

(defn exception-handler
  "Handles exceptions."
  [f]

  (fn [^Exception ex data request]
    (log/error (json/generate-string {:request-id log-helper/*request-id*
                                      :error    ex}))

    (f (.getMessage ex))))

1 个答案:

答案 0 :(得分:6)

在这方面,应用程序会有不同的需求,但一种策略可以是使用Throwable->map

(Throwable->map 
  (ex-info 
    "The Holy Grail me be found in the castle of-aaaaaaaaaaaaaaaarrrgh" 
    {:film "Monty Python and the Holy Grail (1975)"} 
    (IllegalStateException. "aaaaargh")))
=> 
{:cause "aaaaargh",
 :via
 [{:type clojure.lang.ExceptionInfo,
   :message
   "The Holy Grail me be found in the castle of-aaaaaaaaaaaaaaaarrrgh",
   :data {:film "Monty Python and the Holy Grail (1975)"},
   :at [clojure.core$ex_info invokeStatic "core.clj" 4739]}
  {:type java.lang.IllegalStateException,
   :message "aaaaargh",
   :at [user$eval13 invokeStatic "NO_SOURCE_FILE" 2]}],
 :trace
 [[user$eval13 invokeStatic "NO_SOURCE_FILE" 2]
  [user$eval13 invoke "NO_SOURCE_FILE" 2]
  [clojure.lang.Compiler eval "Compiler.java" 7062]
  [clojure.lang.Compiler eval "Compiler.java" 7025]
  [clojure.core$eval invokeStatic "core.clj" 3206]
  [clojure.core$eval invoke "core.clj" 3202]
  [clojure.main$repl$read_eval_print__8572$fn__8575
   invoke
   "main.clj"
   243]
  [clojure.main$repl$read_eval_print__8572 invoke "main.clj" 243]
  [clojure.main$repl$fn__8581 invoke "main.clj" 261]
  [clojure.main$repl invokeStatic "main.clj" 261]
  [clojure.main$repl_opt invokeStatic "main.clj" 325]
  [clojure.main$main invokeStatic "main.clj" 424]
  [clojure.main$main doInvoke "main.clj" 387]
  [clojure.lang.RestFn invoke "RestFn.java" 397]
  [clojure.lang.AFn applyToHelper "AFn.java" 152]
  [clojure.lang.RestFn applyTo "RestFn.java" 132]
  [clojure.lang.Var applyTo "Var.java" 702]
  [clojure.main main "main.java" 37]]}

如果您想制作例外的自定义数据表示,我建议您查看source of Throwable->map以了解如何获取相关信息。