【问题标题】:Error handling with multiple function calls in ClojureClojure 中多个函数调用的错误处理
【发布时间】:2012-09-27 19:08:35
【问题描述】:

我一直在努力寻找在 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 中处理?

【问题讨论】:

    标签: clojure


    【解决方案1】:

    如果它们抛出异常,您可以在 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)})
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2015-02-28
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-08-28
      • 2019-11-06
      • 2023-02-04
      相关资源
      最近更新 更多