blob: ec180438bcb9ccea10f98c494444bbde265d2a49 (
plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
|
;; Copyright (c) Stephen C. Gilardi. All rights reserved. The use and
;; distribution terms for this software are covered by the Eclipse Public
;; License 1.0 (http://opensource.org/licenses/eclipse-1.0.php) which can
;; be found in the file epl-v10.html at the root of this distribution. By
;; using this software in any fashion, you are agreeing to be bound by the
;; terms of this license. You must not remove this notice, or any other,
;; from this software.
;;
;; except.clj
;;
;; Provides functions that make it easy to specify the class and message
;; when throwing an Exception or Error. The optional message is formatted
;; using clojure/format.
;;
;; scgilardi (gmail)
;; Created 07 July 2008
(ns clojure.contrib.except
(:import (clojure.lang Reflector)))
(declare throwable)
(defn throwf
"Throws an Exception or Error with an optional message formatted using
clojure/format. All arguments are optional:
class? format? format-args*
- class defaults to Exception, if present it must name a kind of
Throwable
- format is a format string for clojure/format
- format-args are objects that correspond to format specifiers in
format."
[& args]
(throw (throwable args)))
(defn throw-if
"Throws an Exception or Error if test is true. args are those documented
for throwf."
[test & args]
(when test
(throw (throwable args))))
(defn throw-if-not
"Throws an Exception or Error if test is false. args are those documented
for throwf."
[test & args]
(when-not test
(throw (throwable args))))
(defn throw-arg
"Throws an IllegalArgumentException. All arguments are optional:
format? format-args*
- format is a format string for clojure/format
- format-args are objects that correspond to format specifiers in
format."
[& args]
(throw (throwable (cons IllegalArgumentException args))))
(defn- throwable
"Constructs a Throwable with an optional formatted message. Its stack
trace will begin with our caller's caller. Args are as described for
throwf except throwable accepts them as list rather than inline."
[args]
(let [[class & [fmt & fmt-args]] (if (class? (first args))
args
(cons Exception args))
ctor-args (into-array (if fmt [(apply format fmt fmt-args)] []))
throwable (Reflector/invokeConstructor class ctor-args)
our-prefix "clojure.contrib.except$throwable"
not-us? #(not (.startsWith (.getClassName %) our-prefix))
raw-trace (.getStackTrace throwable)
edited-trace (into-array StackTraceElement
(drop 3 (drop-while not-us? raw-trace)))]
(.setStackTrace throwable edited-trace)
throwable))
|