├── .gitignore ├── .java-version ├── .travis.yml ├── CHANGELOG.md ├── CONTRIBUTING.md ├── LICENSE ├── README.md ├── RELEASING.md ├── project.clj ├── src ├── clj │ └── com │ │ └── rpl │ │ ├── defexception.clj │ │ └── defexception │ │ └── impl.clj └── java │ └── com │ └── rpl │ └── defexception │ └── IDefException.java └── test └── com └── rpl ├── defexception └── other_test.clj └── defexception_test.clj /.gitignore: -------------------------------------------------------------------------------- 1 | /target 2 | /classes 3 | /checkouts 4 | pom.xml 5 | pom.xml.asc 6 | *.jar 7 | *.class 8 | /.lein-* 9 | /.nrepl-port 10 | /.idea 11 | /*.iml 12 | 13 | *~ -------------------------------------------------------------------------------- /.java-version: -------------------------------------------------------------------------------- 1 | 1.8 2 | -------------------------------------------------------------------------------- /.travis.yml: -------------------------------------------------------------------------------- 1 | language: clojure 2 | lein: lein 3 | script: lein with-profile dev:1.4:1.5:1.6:1.7:1.8:1.9 test -------------------------------------------------------------------------------- /CHANGELOG.md: -------------------------------------------------------------------------------- 1 | # Changelog 2 | 3 | ## [Unreleased] 4 | 5 | ## [0.2.5] — 2022-11-04 6 | ### Fixed 7 | - Use boolean, not instance, in constructor cache key 8 | 9 | ## [0.2.4] — 2021-09-28 10 | ### Fixed 11 | - release using jdk 1.8 12 | 13 | ## [0.2.3] — 2021-09-28 14 | ### Fixed 15 | - removed reflection 16 | 17 | ## [0.2.2] — 2020-12-23 18 | ### Changed 19 | - Add IDefException interface on generated exception classes 20 | 21 | ## [0.2.1] — 2020-08-26 22 | ### Changed 23 | - update to clojure 1.10.1 24 | 25 | ## [0.2.0] - 2020-01-29 26 | ### Changed 27 | - Make the stack trace start at the point of instantiation 28 | - Override toString to include the class name 29 | 30 | ## 0.1.0 - 2019-08-22 31 | 32 | [0.2.0]: https://github.com/redplanetlabs/defexception/compare/0.1.0...0.2.0 33 | [0.2.1]: https://github.com/redplanetlabs/defexception/compare/0.2.0...0.2.1 34 | [0.2.2]: https://github.com/redplanetlabs/defexception/compare/0.2.1...0.2.2 35 | [0.2.3]: https://github.com/redplanetlabs/defexception/compare/0.2.2...0.2.3 36 | [0.2.4]: https://github.com/redplanetlabs/defexception/compare/0.2.3...0.2.4 37 | [0.2.5]: https://github.com/redplanetlabs/defexception/compare/0.2.4...0.2.5 38 | [Unreleased]: https://github.com/redplanetlabs/defexception/compare/0.2.5...HEAD 39 | -------------------------------------------------------------------------------- /CONTRIBUTING.md: -------------------------------------------------------------------------------- 1 | # Contributing 2 | 3 | We welcome external contributions to this project. For ideas for new functionality, we recommend first opening an issue so we can discuss whether it makes sense for the project. 4 | 5 | ## Contribution process 6 | 7 | 1. Open a pull request. If possible, please include thorough tests of the new code. 8 | 2. If you have not already signed a contributor agreement, we will request that you sign one. We use Adobe Sign for this so it's very quick and easy. Note that we cannot look at your pull request until a contributor agreement is signed. 9 | 3. We will then review your pull request and possibly ask for changes. 10 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | THE ACCOMPANYING PROGRAM IS PROVIDED UNDER THE TERMS OF THIS ECLIPSE PUBLIC 2 | LICENSE ("AGREEMENT"). ANY USE, REPRODUCTION OR DISTRIBUTION OF THE PROGRAM 3 | CONSTITUTES RECIPIENT'S ACCEPTANCE OF THIS AGREEMENT. 4 | 5 | 1. DEFINITIONS 6 | 7 | "Contribution" means: 8 | 9 | a) in the case of the initial Contributor, the initial code and 10 | documentation distributed under this Agreement, and 11 | 12 | b) in the case of each subsequent Contributor: 13 | 14 | i) changes to the Program, and 15 | 16 | ii) additions to the Program; 17 | 18 | where such changes and/or additions to the Program originate from and are 19 | distributed by that particular Contributor. A Contribution 'originates' from 20 | a Contributor if it was added to the Program by such Contributor itself or 21 | anyone acting on such Contributor's behalf. Contributions do not include 22 | additions to the Program which: (i) are separate modules of software 23 | distributed in conjunction with the Program under their own license 24 | agreement, and (ii) are not derivative works of the Program. 25 | 26 | "Contributor" means any person or entity that distributes the Program. 27 | 28 | "Licensed Patents" mean patent claims licensable by a Contributor which are 29 | necessarily infringed by the use or sale of its Contribution alone or when 30 | combined with the Program. 31 | 32 | "Program" means the Contributions distributed in accordance with this 33 | Agreement. 34 | 35 | "Recipient" means anyone who receives the Program under this Agreement, 36 | including all Contributors. 37 | 38 | 2. GRANT OF RIGHTS 39 | 40 | a) Subject to the terms of this Agreement, each Contributor hereby grants 41 | Recipient a non-exclusive, worldwide, royalty-free copyright license to 42 | reproduce, prepare derivative works of, publicly display, publicly perform, 43 | distribute and sublicense the Contribution of such Contributor, if any, and 44 | such derivative works, in source code and object code form. 45 | 46 | b) Subject to the terms of this Agreement, each Contributor hereby grants 47 | Recipient a non-exclusive, worldwide, royalty-free patent license under 48 | Licensed Patents to make, use, sell, offer to sell, import and otherwise 49 | transfer the Contribution of such Contributor, if any, in source code and 50 | object code form. This patent license shall apply to the combination of the 51 | Contribution and the Program if, at the time the Contribution is added by the 52 | Contributor, such addition of the Contribution causes such combination to be 53 | covered by the Licensed Patents. The patent license shall not apply to any 54 | other combinations which include the Contribution. No hardware per se is 55 | licensed hereunder. 56 | 57 | c) Recipient understands that although each Contributor grants the licenses 58 | to its Contributions set forth herein, no assurances are provided by any 59 | Contributor that the Program does not infringe the patent or other 60 | intellectual property rights of any other entity. Each Contributor disclaims 61 | any liability to Recipient for claims brought by any other entity based on 62 | infringement of intellectual property rights or otherwise. As a condition to 63 | exercising the rights and licenses granted hereunder, each Recipient hereby 64 | assumes sole responsibility to secure any other intellectual property rights 65 | needed, if any. For example, if a third party patent license is required to 66 | allow Recipient to distribute the Program, it is Recipient's responsibility 67 | to acquire that license before distributing the Program. 68 | 69 | d) Each Contributor represents that to its knowledge it has sufficient 70 | copyright rights in its Contribution, if any, to grant the copyright license 71 | set forth in this Agreement. 72 | 73 | 3. REQUIREMENTS 74 | 75 | A Contributor may choose to distribute the Program in object code form under 76 | its own license agreement, provided that: 77 | 78 | a) it complies with the terms and conditions of this Agreement; and 79 | 80 | b) its license agreement: 81 | 82 | i) effectively disclaims on behalf of all Contributors all warranties and 83 | conditions, express and implied, including warranties or conditions of title 84 | and non-infringement, and implied warranties or conditions of merchantability 85 | and fitness for a particular purpose; 86 | 87 | ii) effectively excludes on behalf of all Contributors all liability for 88 | damages, including direct, indirect, special, incidental and consequential 89 | damages, such as lost profits; 90 | 91 | iii) states that any provisions which differ from this Agreement are offered 92 | by that Contributor alone and not by any other party; and 93 | 94 | iv) states that source code for the Program is available from such 95 | Contributor, and informs licensees how to obtain it in a reasonable manner on 96 | or through a medium customarily used for software exchange. 97 | 98 | When the Program is made available in source code form: 99 | 100 | a) it must be made available under this Agreement; and 101 | 102 | b) a copy of this Agreement must be included with each copy of the Program. 103 | 104 | Contributors may not remove or alter any copyright notices contained within 105 | the Program. 106 | 107 | Each Contributor must identify itself as the originator of its Contribution, 108 | if any, in a manner that reasonably allows subsequent Recipients to identify 109 | the originator of the Contribution. 110 | 111 | 4. COMMERCIAL DISTRIBUTION 112 | 113 | Commercial distributors of software may accept certain responsibilities with 114 | respect to end users, business partners and the like. While this license is 115 | intended to facilitate the commercial use of the Program, the Contributor who 116 | includes the Program in a commercial product offering should do so in a 117 | manner which does not create potential liability for other Contributors. 118 | Therefore, if a Contributor includes the Program in a commercial product 119 | offering, such Contributor ("Commercial Contributor") hereby agrees to defend 120 | and indemnify every other Contributor ("Indemnified Contributor") against any 121 | losses, damages and costs (collectively "Losses") arising from claims, 122 | lawsuits and other legal actions brought by a third party against the 123 | Indemnified Contributor to the extent caused by the acts or omissions of such 124 | Commercial Contributor in connection with its distribution of the Program in 125 | a commercial product offering. The obligations in this section do not apply 126 | to any claims or Losses relating to any actual or alleged intellectual 127 | property infringement. In order to qualify, an Indemnified Contributor must: 128 | a) promptly notify the Commercial Contributor in writing of such claim, and 129 | b) allow the Commercial Contributor to control, and cooperate with the 130 | Commercial Contributor in, the defense and any related settlement 131 | negotiations. The Indemnified Contributor may participate in any such claim 132 | at its own expense. 133 | 134 | For example, a Contributor might include the Program in a commercial product 135 | offering, Product X. That Contributor is then a Commercial Contributor. If 136 | that Commercial Contributor then makes performance claims, or offers 137 | warranties related to Product X, those performance claims and warranties are 138 | such Commercial Contributor's responsibility alone. Under this section, the 139 | Commercial Contributor would have to defend claims against the other 140 | Contributors related to those performance claims and warranties, and if a 141 | court requires any other Contributor to pay any damages as a result, the 142 | Commercial Contributor must pay those damages. 143 | 144 | 5. NO WARRANTY 145 | 146 | EXCEPT AS EXPRESSLY SET FORTH IN THIS AGREEMENT, THE PROGRAM IS PROVIDED ON 147 | AN "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, EITHER 148 | EXPRESS OR IMPLIED INCLUDING, WITHOUT LIMITATION, ANY WARRANTIES OR 149 | CONDITIONS OF TITLE, NON-INFRINGEMENT, MERCHANTABILITY OR FITNESS FOR A 150 | PARTICULAR PURPOSE. Each Recipient is solely responsible for determining the 151 | appropriateness of using and distributing the Program and assumes all risks 152 | associated with its exercise of rights under this Agreement , including but 153 | not limited to the risks and costs of program errors, compliance with 154 | applicable laws, damage to or loss of data, programs or equipment, and 155 | unavailability or interruption of operations. 156 | 157 | 6. DISCLAIMER OF LIABILITY 158 | 159 | EXCEPT AS EXPRESSLY SET FORTH IN THIS AGREEMENT, NEITHER RECIPIENT NOR ANY 160 | CONTRIBUTORS SHALL HAVE ANY LIABILITY FOR ANY DIRECT, INDIRECT, INCIDENTAL, 161 | SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING WITHOUT LIMITATION 162 | LOST PROFITS), HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN 163 | CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) 164 | ARISING IN ANY WAY OUT OF THE USE OR DISTRIBUTION OF THE PROGRAM OR THE 165 | EXERCISE OF ANY RIGHTS GRANTED HEREUNDER, EVEN IF ADVISED OF THE POSSIBILITY 166 | OF SUCH DAMAGES. 167 | 168 | 7. GENERAL 169 | 170 | If any provision of this Agreement is invalid or unenforceable under 171 | applicable law, it shall not affect the validity or enforceability of the 172 | remainder of the terms of this Agreement, and without further action by the 173 | parties hereto, such provision shall be reformed to the minimum extent 174 | necessary to make such provision valid and enforceable. 175 | 176 | If Recipient institutes patent litigation against any entity (including a 177 | cross-claim or counterclaim in a lawsuit) alleging that the Program itself 178 | (excluding combinations of the Program with other software or hardware) 179 | infringes such Recipient's patent(s), then such Recipient's rights granted 180 | under Section 2(b) shall terminate as of the date such litigation is filed. 181 | 182 | All Recipient's rights under this Agreement shall terminate if it fails to 183 | comply with any of the material terms or conditions of this Agreement and 184 | does not cure such failure in a reasonable period of time after becoming 185 | aware of such noncompliance. If all Recipient's rights under this Agreement 186 | terminate, Recipient agrees to cease use and distribution of the Program as 187 | soon as reasonably practicable. However, Recipient's obligations under this 188 | Agreement and any licenses granted by Recipient relating to the Program shall 189 | continue and survive. 190 | 191 | Everyone is permitted to copy and distribute copies of this Agreement, but in 192 | order to avoid inconsistency the Agreement is copyrighted and may only be 193 | modified in the following manner. The Agreement Steward reserves the right to 194 | publish new versions (including revisions) of this Agreement from time to 195 | time. No one other than the Agreement Steward has the right to modify this 196 | Agreement. The Eclipse Foundation is the initial Agreement Steward. The 197 | Eclipse Foundation may assign the responsibility to serve as the Agreement 198 | Steward to a suitable separate entity. Each new version of the Agreement will 199 | be given a distinguishing version number. The Program (including 200 | Contributions) may always be distributed subject to the version of the 201 | Agreement under which it was received. In addition, after a new version of 202 | the Agreement is published, Contributor may elect to distribute the Program 203 | (including its Contributions) under the new version. Except as expressly 204 | stated in Sections 2(a) and 2(b) above, Recipient receives no rights or 205 | licenses to the intellectual property of any Contributor under this 206 | Agreement, whether expressly, by implication, estoppel or otherwise. All 207 | rights in the Program not expressly granted under this Agreement are 208 | reserved. 209 | 210 | This Agreement is governed by the laws of the State of New York and the 211 | intellectual property laws of the United States of America. No party to this 212 | Agreement will bring a legal action under this Agreement more than one year 213 | after the cause of action arose. Each party waives its rights to a jury trial 214 | in any resulting litigation. 215 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # defexception 2 | [![Build Status](https://travis-ci.org/redplanetlabs/defexception.svg?branch=master)](https://travis-ci.org/redplanetlabs/defexception) 3 | [![Clojars Project](https://img.shields.io/clojars/v/com.rpl/defexception.svg)](https://clojars.org/com.rpl/defexception) 4 | [![cljdoc 5 | badge](https://cljdoc.org/badge/com.rpl/defexception)](https://cljdoc.org/d/com.rpl/defexception/CURRENT) 6 | 7 | A simple Clojure library that allows one to dynamically define Java Exception classes in Clojure. 8 | 9 | ## Motivation 10 | 11 | Sometimes you just want a quick Exception class that you can catch 12 | directly. `defexception` uses Java bytecode to dynamically create a 13 | Java class that directly inherits from `clojure.lang.ExceptionInfo`. 14 | 15 | The created exception class does not add any behavior to `clojure.lang.ExceptionInfo`. 16 | 17 | ## Dependency 18 | 19 | 20 | [deps.edn](https://clojure.org/guides/deps_and_cli) dependency information: 21 | 22 | ``` 23 | com.rpl/defexception {:mvn/version "0.2.5"} 24 | ``` 25 | 26 | [Leiningen](https://github.com/technomancy/leiningen/) dependency information: 27 | 28 | ``` 29 | [com.rpl/defexception "0.2.5"] 30 | ``` 31 | 32 | ## Usage 33 | 34 | To create your own exception class you can do this: 35 | 36 | ```clojure 37 | (ns foo.bar 38 | (:require [com.rpl.defexception :refer [defexception]])) 39 | 40 | (defexception MyException) 41 | ``` 42 | 43 | This will create the `foo.bar.MyException` class that inherits from 44 | `clojure.lang.ExceptionInfo`. This will also `import` the class into 45 | the current namespace and create a helper function 46 | `foo.bar/->MyException` to help you construct the exception class. 47 | 48 | Now you can do this: 49 | 50 | ```clojure 51 | (try 52 | (throw (->MyException "My bad!" {:my-bad 1})) 53 | (catch MyException e 54 | (ex-data e))) 55 | ;; => {:my-bad 1} 56 | ``` 57 | 58 | The generated `->MyException` helper function has several signatures 59 | to help you instantiate your exception. 60 | 61 | ```clojure 62 | ;; creates an exception with no message or ex-data 63 | (->MyException) 64 | 65 | ;; creates an exception with only ex-data 66 | (->MyException {:hello 1}) 67 | 68 | ;; creates an exception with only a message 69 | (->MyException "My Bad!") 70 | 71 | ;; creates an exception with both a message and ex-data 72 | (->MyException "My Bad!" {:hello 1}) 73 | 74 | ;; creates an exception with a message, ex-data and a cause 75 | (->MyException "My Bad!" {:hello 1} (Exception. "The cause")) 76 | ``` 77 | 78 | ## AOT compilation 79 | 80 | Care was taken to make these exceptions compatible with Clojure's AOT 81 | compilation. 82 | 83 | ## License 84 | 85 | Copyright © 2019 - 2020 Red Planet Labs Inc. 86 | 87 | Distributed under the Eclipse Public License version 1.0 88 | -------------------------------------------------------------------------------- /RELEASING.md: -------------------------------------------------------------------------------- 1 | To release `defexception`, we use `lein release`. 2 | 3 | `defexception` uses java, and the jar will contain a class file, so to 4 | ensure usability with java versions down to 1.8, ensure that you are 5 | using a java 1.8 version. If you use [`jenv`](https://www.jenv.be/), 6 | this should be automatic. 7 | 8 | You will need to ensure that you have credentials configured for clojars 9 | using the "releases" alias. See `lein help deploy" under "Authentication". 10 | -------------------------------------------------------------------------------- /project.clj: -------------------------------------------------------------------------------- 1 | (defproject com.rpl/defexception "0.2.5" 2 | :description "A simple Clojure library that allows one to dynamically define Java Exception classes in Clojure." 3 | :url "https://github.com/redplanetlabs/defexception" 4 | :license {:name "Eclipse Public License" 5 | :url "http://www.eclipse.org/legal/epl-v10.html"} 6 | :scm {:name "git" :url "https://github.com/redplanetlabs/defexception"} 7 | :dependencies [] 8 | :source-paths ["src/clj"] 9 | :java-source-paths ["src/java"] 10 | :plugins [#_[lein-cloverage "1.0.13"] 11 | [lein-shell "0.5.0"] 12 | [lein-ancient "0.6.15"] 13 | [lein-changelog "0.3.2"]] 14 | :profiles {:dev {:dependencies [[org.clojure/clojure "1.10.1"]]} 15 | :1.2 {:dependencies [[org.clojure/clojure "1.2.0"]]} 16 | :1.3 {:dependencies [[org.clojure/clojure "1.3.0"]]} 17 | :1.4 {:dependencies [[org.clojure/clojure "1.4.0"]]} 18 | :1.5 {:dependencies [[org.clojure/clojure "1.5.0"]]} 19 | :1.6 {:dependencies [[org.clojure/clojure "1.6.0"]]} 20 | :1.7 {:dependencies [[org.clojure/clojure "1.7.0"]]} 21 | :1.8 {:dependencies [[org.clojure/clojure "1.8.0"]]} 22 | :1.9 {:dependencies [[org.clojure/clojure "1.9.0"]]}} 23 | :deploy-repositories [["releases" :clojars]] 24 | :aliases {"update-readme-version" 25 | ["shell" "sed" "-I" ".bak" 26 | "-e" "s/defexception \"[0-9.]*\"/defexception \"${:version}\"/" 27 | "-e" "s/version \"[0-9.]*\"/version \"${:version}\"/" 28 | "README.md"]} 29 | :release-tasks [["shell" "git" "diff" "--exit-code"] 30 | ["change" "version" "leiningen.release/bump-version"] 31 | ["change" "version" "leiningen.release/bump-version" "release"] 32 | ["changelog" "release"] 33 | ["update-readme-version"] 34 | ["vcs" "commit"] 35 | ["vcs" "tag" "--no-sign"] 36 | ["deploy"] 37 | ["vcs" "push"]]) 38 | -------------------------------------------------------------------------------- /src/clj/com/rpl/defexception.clj: -------------------------------------------------------------------------------- 1 | (ns com.rpl.defexception 2 | (:require [clojure.string :as string] 3 | [com.rpl.defexception.impl :as impl])) 4 | 5 | (defmacro defexception 6 | "Dynamically creates an clojure.lang.ExceptionInfo class using JVM 7 | bytecode. The exception class inherits its behavior from 8 | clojure.lang.ExceptionInfo yet will be its own type. 9 | 10 | This means that an instance of this exception will respond to 11 | `clojure.core/ex-data` and can have an optional Throwable `cause` arg. 12 | 13 | This will create a constructor function much similar to the one 14 | created for Records. 15 | 16 | Example Usage: 17 | 18 | (defexception MyException) => user.MyException 19 | 20 | (->MyException) 21 | (->MyException {:hello 1}) 22 | (->MyException \"This is a message\") 23 | (->MyException \"This is a message\" {:hello 1}) 24 | (->MyException \"This is a message\" {:hello 1} (Exception. \"A cause\")) 25 | 26 | (ex-data (->MyException {:hello 1})) => {:hello 1} 27 | 28 | (ex-data (->MyException \"This is a message\" {:hello 1})) => {:hello 1} 29 | 30 | (.getMessage (->MyException \"This is a message\")) => \"This is a message\" 31 | 32 | or invoke the constructors directly 33 | 34 | (user/MyException. \"This is a Message\" {}) 35 | (user/MyException. \"This is a Message\" {} (Exception. \"A message\"))" 36 | [t] 37 | (let [class-name (str (string/replace (str *ns*) "-" "_") "." t)] 38 | `(let [x# (impl/load-or-mk-ex-info-class ~class-name)] 39 | (import ~(symbol class-name)) 40 | (defn ~(symbol (str "->" t)) 41 | ([] (impl/make-ex x# nil {} nil)) 42 | ([~'msg-o-data] 43 | (if (map? ~'msg-o-data) 44 | (impl/make-ex x# nil ~'msg-o-data nil) 45 | (impl/make-ex x# ~'msg-o-data {} nil))) 46 | ([~'msg ~'data] (impl/make-ex x# ~'msg ~'data nil)) 47 | ([~'msg ~'data ~'cause] (impl/make-ex x# ~'msg ~'data ~'cause))) 48 | x#))) 49 | -------------------------------------------------------------------------------- /src/clj/com/rpl/defexception/impl.clj: -------------------------------------------------------------------------------- 1 | (ns ^:no-doc com.rpl.defexception.impl 2 | (:require [clojure.string :as string]) 3 | (:import [clojure.asm MethodVisitor 4 | ClassVisitor ClassWriter Opcodes Type] 5 | [clojure.asm.commons GeneratorAdapter Method] 6 | [clojure.lang ExceptionInfo] 7 | [com.rpl.defexception IDefException])) 8 | 9 | (defn- forward-constructor [^ClassWriter cw ^Type t ^Method constr] 10 | (doto (GeneratorAdapter. Opcodes/ACC_PUBLIC constr nil nil cw) 11 | (.loadThis) 12 | (.loadArgs) 13 | (.invokeConstructor t constr) 14 | (.returnValue) 15 | (.endMethod))) 16 | 17 | (defn- to-string-method [^ClassWriter cw ^String exception-class-name] 18 | (let [string (Type/getType String) 19 | string-builder (Type/getType StringBuilder) 20 | string-append (Method/getMethod 21 | "java.lang.StringBuilder append (java.lang.String)") 22 | to-string (Method/getMethod "java.lang.String toString ()")] 23 | (doto (GeneratorAdapter. Opcodes/ACC_PUBLIC to-string nil nil cw) 24 | (.newInstance string) 25 | (.dup) 26 | 27 | (.newInstance string-builder) 28 | (.dup) 29 | (.invokeConstructor string-builder (Method/getMethod "void ()")) 30 | 31 | (.push (str exception-class-name ": ")) 32 | (.invokeVirtual string-builder string-append) 33 | 34 | (.loadThis) 35 | (.invokeVirtual (Type/getType Exception) (Method/getMethod "String getMessage ()")) 36 | (.invokeVirtual string-builder string-append) 37 | 38 | (.push " ") 39 | (.invokeVirtual string-builder string-append) 40 | 41 | (.loadThis) 42 | (.getField (Type/getType clojure.lang.ExceptionInfo) 43 | "data" 44 | (Type/getType clojure.lang.IPersistentMap)) 45 | (.invokeVirtual (Type/getType Object) to-string) 46 | (.invokeVirtual string-builder string-append) 47 | 48 | (.invokeConstructor 49 | string 50 | (Method/getMethod "void (java.lang.StringBuilder)")) 51 | 52 | (.returnValue) 53 | (.endMethod)))) 54 | 55 | (defn- define-class [^clojure.lang.DynamicClassLoader cl ^String name ^ClassWriter cw] 56 | (let [klass (.defineClass cl name (.toByteArray cw) nil)] 57 | (when *compile-files* 58 | (clojure.lang.Compiler/writeClassFile 59 | (string/replace (munge (.getName klass)) "." "/") 60 | (.toByteArray cw))) 61 | klass)) 62 | 63 | (defn- mk-ex-info-class [exception-class-name] 64 | #_(prn :making exception-class-name) 65 | (let [cw (ClassWriter. (+ ClassWriter/COMPUTE_MAXS ClassWriter/COMPUTE_FRAMES)) 66 | ex-info-type (Type/getType clojure.lang.ExceptionInfo) 67 | internal-name (string/replace exception-class-name "." "/") 68 | class-name (-> internal-name (string/split #"/") last)] 69 | (.visit cw 70 | ;; this allows compatibility back to Clojure 1.4 71 | ;; and is = clojure.asm.Opcodes/V1_7 72 | (inc clojure.asm.Opcodes/V1_6) 73 | (+ Opcodes/ACC_SUPER Opcodes/ACC_PUBLIC) 74 | internal-name 75 | nil 76 | (.getInternalName ex-info-type) 77 | (into-array String [(Type/getInternalName IDefException)])) 78 | (forward-constructor 79 | cw 80 | ex-info-type 81 | (Method/getMethod "void (String, clojure.lang.IPersistentMap)")) 82 | (forward-constructor 83 | cw 84 | ex-info-type 85 | (Method/getMethod "void (String, clojure.lang.IPersistentMap, Throwable)")) 86 | (to-string-method 87 | cw 88 | class-name) 89 | (.visitEnd cw) 90 | (define-class 91 | (clojure.lang.DynamicClassLoader.) 92 | exception-class-name 93 | cw))) 94 | 95 | (defn load-or-mk-ex-info-class [exception-class-name] 96 | (try (clojure.lang.RT/classForName exception-class-name) 97 | (catch ClassNotFoundException e 98 | (mk-ex-info-class exception-class-name)))) 99 | 100 | (def ^:private ex-info-const 101 | (memoize 102 | (fn [^Class klass cause?] 103 | (assert (boolean? cause?)) 104 | (let [arg-types [String clojure.lang.IPersistentMap]] 105 | (.getConstructor 106 | klass 107 | (into-array Class 108 | (if cause? 109 | (conj arg-types Throwable) 110 | arg-types))))))) 111 | 112 | (defn- fix-stack-trace [^ExceptionInfo ex-info-instance] 113 | (let [stacktrace (.getStackTrace ex-info-instance) 114 | constructor-pattern (re-pattern 115 | (str ".*" 116 | (munge 117 | (str "->" 118 | (-> ex-info-instance 119 | class 120 | (.getSimpleName)))) 121 | ".*")) 122 | updated-stacktrace (->> stacktrace 123 | (drop-while 124 | (fn [^StackTraceElement elt] 125 | (not 126 | (re-matches 127 | constructor-pattern 128 | (.getClassName elt))))) 129 | rest 130 | (into-array StackTraceElement))] 131 | (when stacktrace 132 | (.setStackTrace ex-info-instance updated-stacktrace)) 133 | ex-info-instance) 134 | ) 135 | 136 | (defn make-ex 137 | "use reflection to instantiate the exception class" 138 | [^Class klass msg data cause] 139 | (let [constr ^java.lang.reflect.Constructor (ex-info-const klass (boolean cause)) 140 | args [msg (or data {})]] 141 | (fix-stack-trace (.newInstance constr 142 | (object-array 143 | (if cause 144 | (conj args cause) 145 | args)))))) 146 | -------------------------------------------------------------------------------- /src/java/com/rpl/defexception/IDefException.java: -------------------------------------------------------------------------------- 1 | package com.rpl.defexception; 2 | 3 | public interface IDefException { 4 | 5 | } 6 | -------------------------------------------------------------------------------- /test/com/rpl/defexception/other_test.clj: -------------------------------------------------------------------------------- 1 | (ns com.rpl.defexception.other-test 2 | (:require [clojure.test :refer :all] 3 | [com.rpl.defexception-test :refer [->TestException]]) 4 | (:import [com.rpl.defexception_test TestException])) 5 | 6 | ;; this is simply testing the import of an exception from a namespace 7 | ;; where it's defined 8 | 9 | (deftest aot-class-test 10 | (let [ex (->TestException)] 11 | (is (= nil (.getMessage ex))) 12 | (is (= {} (ex-data ex)))) 13 | (let [ex (->TestException "Message")] 14 | (is (= "Message" (.getMessage ex))) 15 | (is (= {} (ex-data ex)))) 16 | (let [ex (->TestException {:hello 1})] 17 | (is (= nil (.getMessage ex))) 18 | (is (= {:hello 1} (ex-data ex)))) 19 | (let [ex (->TestException "Message" {:hello 1})] 20 | (is (= "Message" (.getMessage ex))) 21 | (is (= {:hello 1} (ex-data ex)))) 22 | (let [cause (Exception. "Cause") 23 | ex (->TestException "Message" {:hello 1} cause)] 24 | (is (= "Message" (.getMessage ex))) 25 | (is (= {:hello 1} (ex-data ex))) 26 | (is (= cause (.getCause ex))))) 27 | 28 | 29 | 30 | -------------------------------------------------------------------------------- /test/com/rpl/defexception_test.clj: -------------------------------------------------------------------------------- 1 | (ns com.rpl.defexception-test 2 | (:require [clojure.test :refer :all] 3 | [com.rpl.defexception :refer [defexception]] 4 | [clojure.java.io :as io]) 5 | (:import [com.rpl.defexception IDefException])) 6 | 7 | (defexception MyException) 8 | 9 | (binding [*compile-files* true] 10 | (defexception TestException)) 11 | 12 | (deftest dynamic-exception-class-test 13 | (let [ex (MyException. "Message" {:hello 1})] 14 | (is (instance? IDefException ex)) 15 | (is (= "Message" (.getMessage ex))) 16 | (is (= {:hello 1} (ex-data ex))) 17 | (is (= "MyException: Message {:hello 1}" (str ex)))) 18 | (let [cause (Exception. "Cause") 19 | ex (MyException. "Message" {:hello 1} cause)] 20 | (is (not (instance? IDefException cause))) 21 | (is (= "Message" (.getMessage ex))) 22 | (is (= {:hello 1} (ex-data ex))) 23 | (is (= cause (.getCause ex))) 24 | (is (= "MyException: Message {:hello 1}" (str ex))))) 25 | 26 | (deftest dynamic-exception-class-const-fn 27 | (let [ex (->MyException)] 28 | (is (= nil (.getMessage ex))) 29 | (is (= {} (ex-data ex))) 30 | (is (= "MyException: null {}" (str ex)))) 31 | (let [ex (->MyException "Message")] 32 | (is (= "Message" (.getMessage ex))) 33 | (is (= {} (ex-data ex))) 34 | (is (= "MyException: Message {}" (str ex)))) 35 | (let [ex (->MyException {:hello 1})] 36 | (is (= nil (.getMessage ex))) 37 | (is (= {:hello 1} (ex-data ex))) 38 | (is (= "MyException: null {:hello 1}" (str ex)))) 39 | (let [ex (->MyException "Message" {:hello 1})] 40 | (is (= "Message" (.getMessage ex))) 41 | (is (= {:hello 1} (ex-data ex))) 42 | (is (= "MyException: Message {:hello 1}" (str ex)))) 43 | (let [cause (Exception. "Cause") 44 | ex (->MyException "Message" {:hello 1} cause)] 45 | (is (= "Message" (.getMessage ex))) 46 | (is (= {:hello 1} (ex-data ex))) 47 | (is (= cause (.getCause ex))) 48 | (is (= "MyException: Message {:hello 1}" (str ex))))) 49 | 50 | (deftest has-aoted 51 | (is (.. 52 | (io/file *compile-path* "com/rpl/defexception_test/TestException.class") 53 | exists))) 54 | 55 | (deftest aot-class-test 56 | (let [ex (->TestException)] 57 | (is (= nil (.getMessage ex))) 58 | (is (= {} (ex-data ex))) 59 | (is (= "TestException: null {}" (str ex)))) 60 | (let [ex (->TestException "Message")] 61 | (is (= "Message" (.getMessage ex))) 62 | (is (= {} (ex-data ex))) 63 | (is (= "TestException: Message {}" (str ex)))) 64 | (let [ex (->TestException {:hello 1})] 65 | (is (= nil (.getMessage ex))) 66 | (is (= {:hello 1} (ex-data ex))) 67 | (is (= "TestException: null {:hello 1}" (str ex)))) 68 | (let [ex (->TestException "Message" {:hello 1})] 69 | (is (= "Message" (.getMessage ex))) 70 | (is (= {:hello 1} (ex-data ex))) 71 | (is (= "TestException: Message {:hello 1}" (str ex)))) 72 | (let [cause (Exception. "Cause") 73 | ex (->TestException "Message" {:hello 1} cause)] 74 | (is (= "Message" (.getMessage ex))) 75 | (is (= {:hello 1} (ex-data ex))) 76 | (is (= cause (.getCause ex))) 77 | (is (= "TestException: Message {:hello 1}" (str ex))))) 78 | 79 | (defmacro line [] (-> &form meta :line)) 80 | (defmacro cur-file [] *file*) 81 | 82 | (deftest stack-trace-test 83 | (let [ex (->TestException) 84 | instantiation-line-no (dec (line))] 85 | (try 86 | (throw ex) 87 | (catch TestException e 88 | (let [first-stack-trace-element (first (.getStackTrace e)) 89 | line-no (.getLineNumber first-stack-trace-element) 90 | file-name (.getFileName first-stack-trace-element)] 91 | (is (= instantiation-line-no line-no)) 92 | (is (= (last (clojure.string/split (cur-file) #"/")) file-name)) 93 | )))) 94 | ) 95 | --------------------------------------------------------------------------------