Skip to content

Instantly share code, notes, and snippets.

@kwrooijen
Last active July 14, 2020 15:59
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 kwrooijen/0445ec96295d70f517674ec07281f105 to your computer and use it in GitHub Desktop.
Save kwrooijen/0445ec96295d70f517674ec07281f105 to your computer and use it in GitHub Desktop.
(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