我一直在努力寻找一种在 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 block 中的某个函数内部出现问题(假设没有正确的方法来处理这些函数内部的错误),它们是否应该抛出异常以在 do-stuff 中处理?
最佳答案
如果它们抛出异常,您可以在 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)})
关于clojure - Clojure 中多个函数调用的错误处理,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12628452/