Last active
August 29, 2015 13:56
-
-
Save ahammel/9082228 to your computer and use it in GitHub Desktop.
Macro for a dire.clj handler which catches multiple exception types
This file contains hidden or 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
| (ns multi-handler | |
| (:require [clojure.string :as string] | |
| [dire.core :refer [with-handler!]])) | |
| (defmacro with-multi-handler! | |
| "Make handlers for every exception in a collection" | |
| [handled exceptions body] | |
| (cons 'do | |
| (map | |
| #(list 'with-handler! handled % body) | |
| exceptions))) | |
| (comment | |
| "Motivating example" | |
| (defrecord RiteOfAshkEnte | |
| [number-of-sticks | |
| egg-status]) | |
| (defn str->rite | |
| "Return the rite of Ashk'Ente from a string" | |
| [book-of-lore] | |
| (let [fields (string/split book-of-lore #"\s+")] | |
| (map->RiteOfAshkEnte | |
| {:number-of-sticks (Integer/parseInt (nth fields 0)) | |
| :egg-status (nth fields 1)}))) | |
| (with-multi-handler! #'str->rite | |
| [NumberFormatException | |
| IndexOutOfBoundsException] | |
| (fn [& _] | |
| (println "Your book of lore is poorly-formatted"))) | |
| (str->rite "2 fresh") | |
| ; => RiteOfAshkEnte{:number-of-sticks 2, :egg-status "fresh"} | |
| (str->rite "fresh 2") | |
| ; => "Your book of lore is poorly-formatted" | |
| (str->rite "2") | |
| ; => "Your book of lore is poorly-formatted" | |
| ) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment