Skip to content

Instantly share code, notes, and snippets.

@stain
Last active August 29, 2015 13:58
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save stain/8aa635304664473054bc to your computer and use it in GitHub Desktop.
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.
(defn ensure-int [number]
(try
(Integer/parseInt number)
(catch NumberFormatException e
(throw (ex-info (str "Invalid integer: " number) {:status 400 })))))
(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