clojure - Clojure 中多个函数调用的错误处理

标签 clojure

我一直在努力寻找一种在 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/

相关文章:

list - Clojure:将成对列表/n 元组转换为列表的 n 元组

database - Datomic 元数据中是否有实体,例如创建和更新时间?

pdf - 如何使用ring提供pdf流服务

logging - 如何抑制继承的项目 logback.xml 文件(单个项目中有 2 个 logback.xml)?

clojure - 如何将现有的函数应用到新的类中?

clojure - 这是 Clojure 惯用的吗?

clojure - 在与 Clojure 中运行代码相同的目录中打开文件

android - 什么是 Apache-HttpClient/UNAVAILABLE 错误(Android、Google App Engine)?

windows - Leiningen 终止批处理文件的执行

clojure - 如果那么在 Clojure 中做