-
Notifications
You must be signed in to change notification settings - Fork 0
/
errors.go
93 lines (75 loc) · 1.94 KB
/
errors.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
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
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
package common_utils
import (
"context"
"fmt"
"strconv"
"strings"
"go.opentelemetry.io/otel/attribute"
"go.opentelemetry.io/otel/trace"
"go.uber.org/zap"
)
type AppError struct {
Message string
StatusCode int
}
func (ae *AppError) Error() string {
return fmt.Sprintf("app error: status code %d, message %s", ae.StatusCode, ae.Message)
}
func CustomError(message string, statusCode int) error {
return fmt.Errorf("|%s<->%d", message, statusCode)
}
func CustomErrorWithTrace(err error, message string, statusCode int) error {
return fmt.Errorf("%s|%s<->%d", err.Error(), message, statusCode)
}
func PanicIfError(err error) {
if err != nil {
customError := strings.Split(err.Error(), "<->")
message := customError[0]
statusCode := 500
if len(customError) > 1 {
statusCode, _ = strconv.Atoi(customError[1])
}
appErr := AppError{
Message: message,
StatusCode: statusCode,
}
panic(appErr)
}
}
func PanicIfAppError(err error, message string, statusCode int) {
if err != nil {
customErr := CustomErrorWithTrace(err, message, statusCode)
PanicIfError(customErr)
}
}
func PanicIfAppErrorWithTrace(ctx context.Context, err error, message string, statusCode int) {
if err != nil {
span := trace.SpanFromContext(ctx)
defer span.End()
customErr := CustomErrorWithTrace(err, message, statusCode)
span.RecordError(customErr)
span.SetAttributes(attribute.Bool("error", true))
PanicIfError(customErr)
}
}
func PanicAppError(message string, statusCode int) {
customErr := CustomError(message, statusCode)
PanicIfError(customErr)
}
func DeferCheck(function func() error) {
if err := function(); err != nil {
LogError("defer error", zap.Error(err))
}
}
func LogIfError(err error) {
if err != nil {
LogError("error occurred", zap.Error(err))
}
}
func LogAndPanicIfError(err error, message string) {
if err != nil {
errMsg := fmt.Sprintf("%s :%v", message, err)
LogError(errMsg, zap.Error(err))
panic(err)
}
}