-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathinvariant.go
50 lines (39 loc) · 1.01 KB
/
invariant.go
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
package invariant
import (
"fmt"
"flag"
)
const (
development = "development"
production = "production"
)
type InvariantError struct {
What string
Name string
}
func (e InvariantError) Error() string {
return fmt.Sprintf("%v", e.What)
}
func (e InvariantError) String() string {
return fmt.Sprintf("%v", e.What)
}
func Invariant(condition bool, format string, args ...interface{}) error {
var env string
flag.StringVar(&env, "env", development, "current environment (development or production)")
flag.Parse()
if env != production {
if format == "" {
return InvariantError{"invariant requires an error message argument", "Invariant Violation"}
}
}
if !condition {
var error InvariantError
if env != development {
error = InvariantError{"invariant exception in production environment. Please use development flag to see the full error message", "Invariant Violation"}
} else {
error = InvariantError{fmt.Sprintf(format, args...), "Invariant Violation"}
}
return error
}
return nil
}