Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

idiomatic way to catch exceptions in ring apps

Tags:

clojure

ring

What is the idiomatic way to handle exceptions in ring apps. I would like to capture the exception and return a 500 page. How do I do that ?

I am using moustache for the code below, however it doesnt work -

(def my-app (try
              (app
               (wrap-logger true)
               wrap-keyword-params
               wrap-params
               wrap-file-info
               (wrap-file "resources/public/")
               [""]  (index-route @prev-h nil)
               ["getContent"] (fetch-url)
               ["about"] "We are freaking cool man !!"
               [&] (-> "Nothing was found" response (status 404) constantly))
              (catch Exception e
                (app
                 [&] (-> "This is an error" response (status 500) constantly)))
like image 675
murtaza52 Avatar asked Sep 27 '12 17:09

murtaza52


1 Answers

You don't want to wrap the whole app in a try-catch block, you want to wrap the handling of each request separately. It's quite easy to make a middleware that does this. Something like:

(defn wrap-exception [handler]
  (fn [request]
    (try (handler request)
      (catch Exception e
         {:status 500
          :body "Exception caught"}))))
like image 69
Joost Diepenmaat Avatar answered Oct 20 '22 18:10

Joost Diepenmaat