2012-09-27 36 views
3

我一直在努力找到一種在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有效他們被傳遞給富?

如果在let塊的某個函數內部出現問題(假設沒有正確的方法來處理這些函數中的錯誤),他們是否應該拋出一個異常來處理do-stuff?

回答

4

如果他們拋出異常你可以趕上他們的讓利外:

(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)})