Last active
July 14, 2020 15:59
-
-
Save kwrooijen/0445ec96295d70f517674ec07281f105 to your computer and use it in GitHub Desktop.
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
(defmulti exception->map | |
(fn [^SQLException e] | |
(.getSQLState e))) | |
(defn- remove-quotes [s] | |
(clojure.string/replace s #"\"" "")) | |
(defn sql-key->keyword [sql-key] | |
(-> sql-key | |
(string/replace #"_key$" "") | |
(string/replace-first #"_" "/") | |
(string/replace #"_" "-") | |
(keyword))) | |
(defn sql-error->sql-key [sql-error] | |
(remove-quotes (re-find #"\".*\"" sql-error))) | |
;; Postgres unique_violation | |
;; https://www.postgresql.org/docs/9.2/errcodes-appendix.html | |
(defmethod exception->map "23505" [^SQLException e] | |
{:duplicate-key | |
(-> (.getMessage e) | |
(sql-error->sql-key) | |
(sql-key->keyword))}) | |
(defmethod exception->map :default [^SQLException e] | |
(println "Unhandled SQL execption " | |
(.getSQLState e) "\n " | |
(.getMessage e)) | |
{:unknown [(.getSQLState e)]}) | |
;; Usage: | |
(try | |
(jdbc/execute-one! *database* (sql/format form)) | |
(catch Exception e | |
;; This will return {:duplicate-key :some-table/some-key} if the exception is a 23505 error. | |
(exception->map e))) | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment