...
1
19
20 package precond
21
22 import (
23 "fmt"
24 )
25
26 type PreconditionError struct {
27 msg string
28 }
29
30 func (e *PreconditionError) Error() string {
31 return e.msg
32 }
33
34 func MustNotBeEmpty(str string, msg ...interface{}) string {
35 panicOnError(CheckNotEmpty(str, msg...))
36 return str
37 }
38
39 func MustNotBeNil(obj interface{}, msg ...interface{}) interface{} {
40 panicOnError(CheckNotNil(obj, msg...))
41 return obj
42 }
43
44 func MustBeTrue(b bool, msg ...interface{}) {
45 panicOnError(CheckTrue(b, msg...))
46 }
47
48 func CheckNotEmpty(str string, msg ...interface{}) error {
49 if str == "" {
50 return newError("String must not be empty", msg...)
51 }
52 return nil
53 }
54
55 func CheckNotNil(obj interface{}, msg ...interface{}) error {
56 if obj == nil {
57 return newError("Object must not be nil", msg...)
58 }
59 return nil
60 }
61
62 func CheckTrue(b bool, msg ...interface{}) error {
63 if b == false {
64 return newError("Expression must be true", msg...)
65 }
66 return nil
67 }
68
69 func panicOnError(e error) {
70 if e != nil {
71 panic(e)
72 }
73 }
74
75 func newError(defaultMsg string, msg ...interface{}) *PreconditionError {
76 return &PreconditionError{msg: newErrMsg(defaultMsg, msg...)}
77 }
78
79 func newErrMsg(defaultMsg string, msg ...interface{}) string {
80 if msg != nil {
81 switch t := msg[0].(type) {
82 case string:
83 return fmt.Sprintf(t, msg[1:]...)
84 default:
85 return fmt.Sprint(msg...)
86 }
87 }
88 return defaultMsg
89 }
90
View as plain text