Last active
August 29, 2015 13:58
-
-
Save stain/8aa635304664473054bc to your computer and use it in GitHub Desktop.
A Clojure Ring middleware for catching Exception and using its :status as HTTP status code.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
(defn ensure-int [number] | |
(try | |
(Integer/parseInt number) | |
(catch NumberFormatException e | |
(throw (ex-info (str "Invalid integer: " number) {:status 400 }))))) |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
(defn ex-info-status | |
"Ring Middleware that catches exceptions which minimally contain the (ex-data) key :status. | |
The exception message will be used as body, unless the ex-data contains a :body key. | |
Additional Ring response keys can be used to customize headers, etc. | |
Example: | |
(throw (ex-info \"Resource was deleted.\" { :status 410 })) | |
Redirection: | |
(throw (ex-info nil (ring.util.response/redirect \"http://example.com/\"))) | |
Usage with ring: | |
(def app | |
(-> | |
(handler/site app-routes) | |
(ex-info-status))) | |
" | |
[handler] | |
(fn [request] | |
(try (handler request) | |
(catch Exception e | |
(if (:status (ex-data e)) | |
(merge | |
{ :body (.getMessage e) } | |
(ex-data e)) | |
(throw e)))))) | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment