Karthick R
Karthick R

Reputation: 619

How to catch and rethrow an exception

I have a clojure function which calls another function to update the database.

(^{PUT true
       Path "/{id}"
       Produces ["application/json"]
       Consumes ["application/json"]
       ApiOperation {:value "Update" :notes ""}}
       updateFeedback [this
                       ^{PathParam "id"} id
                       body]
       (require 'com.xx.x.xx.xx.xx-response)
       (let [doc (json/read-json body)]
         (if-let [valid-doc (validate doc)]
                 (try+
                  (->>
                   (assoc valid-doc :modificationDate (Utilities/getCurrentDate))
                   (couch/update-document dbs/xx-db)
                   (core/ok-response))
                  (catch java.io.IOException ex
                         (log/error "line num 197"))
                  (catch java.lang.Exception ex
                         (log/error "line num 200"))))))

The update-document function throws an exception. I would like to throw it back to the caller -- in this case updateFeedback so that the content in the catch block gets executed. For some reason, clojure logs the exception and the catch block in the caller never executes.

To verify I wrapped the code in the update-document function in a try catch block. There the catch block got executed.

How do I add a throws clause to the function?

Update: I have updated the function. Apologies for the syntax issues. I have updated the code we are using. I am not familiar with clojure. This is a code which we inherited and we are asked to fix a bug. Any pointers would be really helpful.

Upvotes: 8

Views: 3420

Answers (1)

bsvingen
bsvingen

Reputation: 2759

If you are trying to catch and then re-throw an exception you can do something like this:

(defn throwing-function
  []
  (/ 7 0))

(defn catching-function
  []
  (try
    (throwing-function)
    (catch Exception e
      (println "Caught exception:" e)
      (println "Re-throwing ...")
      (throw e))))

Upvotes: 13

Related Questions