我一直在努力寻找一种在Clojure中进行错误处理的正确方法,并且喜欢关于这个主题的一些想法。
给出一个没有错误处理的例子:
(defn do-stuff
(let [result1 (some-function)
result2 (other-function)
result3 (yet-another-function)]
{:status 200
:body (foo result1 result2 result3)}))
如果某处出现错误,则应返回以下内容:
{:status 4xx
:body "Some descriptive error message, based on what went wrong"}
如何确保result1-3在传递给foo之前有效?
如果let块中的一个函数内部出现问题(假设没有正确的方法来处理这些函数中的错误),它们是否应该抛出异常以在do-stuff中处理?
答案 0 :(得分:4)
如果他们抛出异常,你可以在let:
之外捕获它们(defn do-stuff
(try
(let [result1 (some-function)
result2 (other-function)
result3 (yet-another-function)]
{:status 200
:body (foo result1 result2 result3)})
(catch MyException e
{:status 4xx
:body (str "Some descriptive error message, " (.getMessage e)})