-
Notifications
You must be signed in to change notification settings - Fork 249
/
bizerror.go
96 lines (82 loc) · 1.92 KB
/
bizerror.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
94
95
96
package rest
import (
"fmt"
"github.com/pkg/errors"
"net/http"
)
// BizError is used for business error implemented error interface
// StatusCode will be set to http response status code
// ErrCode is used for business error code
// ErrMsg is custom error message
type BizError struct {
StatusCode int
ErrCode int
ErrMsg string
Cause error
}
type BizErrorOption func(bizError *BizError)
func WithStatusCode(statusCode int) BizErrorOption {
return func(bizError *BizError) {
bizError.StatusCode = statusCode
}
}
func WithErrCode(errCode int) BizErrorOption {
return func(bizError *BizError) {
bizError.ErrCode = errCode
}
}
func WithCause(cause error) BizErrorOption {
return func(bizError *BizError) {
bizError.Cause = cause
}
}
// NewBizError is factory function for creating an instance of BizError struct
func NewBizError(err error, opts ...BizErrorOption) BizError {
bz := BizError{
ErrCode: 1,
StatusCode: http.StatusInternalServerError,
ErrMsg: err.Error(),
}
for _, fn := range opts {
fn(&bz)
}
return bz
}
// String function is used for printing string representation of a BizError instance
func (b BizError) String() string {
if b.ErrCode > 0 {
return fmt.Sprintf("%d %s", b.ErrCode, b.ErrMsg)
}
return b.ErrMsg
}
// Error is used for implementing error interface
func (b BizError) Error() string {
return b.ErrMsg
}
func HandleBadRequestErr(err error) {
panic(NewBizError(err, WithStatusCode(http.StatusBadRequest)))
}
func HandleInternalServerError(err error) {
panic(NewBizError(err))
}
func PanicBadRequestErr(err error) {
if err == nil {
return
}
panic(NewBizError(err, WithStatusCode(http.StatusBadRequest)))
}
func PanicInternalServerError(err error) {
if err == nil {
return
}
panic(NewBizError(err))
}
func UnWrap(err error) error {
var bizErr BizError
if errors.As(err, &bizErr) {
if bizErr.Cause != nil {
return UnWrap(bizErr.Cause)
}
}
return err
}