-
Notifications
You must be signed in to change notification settings - Fork 0
/
error.go
42 lines (37 loc) · 895 Bytes
/
error.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
// SPDX-License-Identifier: 0BSD
package sx
import (
"errors"
"strings"
)
// Throws an error by panic-ing
func Throw(errorMessages ...string) {
var err error = errors.New(strings.Join(errorMessages, " "))
panic(err)
}
// Throws an error by panic-ing iff the condition is true
func ThrowIf(condition bool, errorMessages ...string) {
if condition {
Throw(errorMessages...)
}
}
func ThrowIfError(err error) {
if err != nil {
panic(err)
}
}
// Catches errors thrown by "Throw" or "ThrowIf", recovers the panic
// Needs to be called before throwing errors
// Only handles errors. If you throw/panic something else, you need to provide a custom recover function
func Catch(handler ...func(error)) {
if x := recover(); x != nil {
var err = TypeCast[error](x)
if len(handler) > 0 && err.Ok() {
for _, h := range handler {
h(err.Value())
}
} else {
panic(x)
}
}
}