1
1
package ginx
2
2
3
3
import (
4
- "errors"
5
4
"github.com/TBXark/sphere/log"
6
5
"github.com/TBXark/sphere/log/logfields"
7
6
"github.com/gin-gonic/gin"
8
7
"net/http"
9
8
)
10
9
11
- var internalServerError = errors .New ("internal server error" )
12
-
13
- type statusError interface {
14
- error
15
- Status () int
16
- }
17
-
18
10
type Context = gin.Context
19
11
20
12
func Value [T any ](key string , ctx * gin.Context ) (* T , bool ) {
@@ -28,19 +20,12 @@ func Value[T any](key string, ctx *gin.Context) (*T, bool) {
28
20
return nil , false
29
21
}
30
22
31
- func AbortWithJsonError (ctx * gin.Context , code int , err error ) {
32
- var hErr statusError
33
- if errors .As (err , & hErr ) {
34
- ctx .AbortWithStatusJSON (hErr .Status (), ErrorResponse {
35
- Code : hErr .Status (),
36
- Message : hErr .Error (),
37
- })
38
- } else {
39
- ctx .AbortWithStatusJSON (code , ErrorResponse {
40
- Code : hErr .Status (),
41
- Message : err .Error (),
42
- })
43
- }
23
+ func AbortWithJsonError (ctx * gin.Context , err error ) {
24
+ code , status , message := parseError (err )
25
+ ctx .AbortWithStatusJSON (status , ErrorResponse {
26
+ Code : code ,
27
+ Message : message ,
28
+ })
44
29
}
45
30
46
31
func WithRecover (message string , handler func (ctx * gin.Context )) func (ctx * gin.Context ) {
@@ -51,7 +36,7 @@ func WithRecover(message string, handler func(ctx *gin.Context)) func(ctx *gin.C
51
36
message ,
52
37
logfields .Any ("error" , err ),
53
38
)
54
- AbortWithJsonError (ctx , http . StatusInternalServerError , internalServerError )
39
+ AbortWithJsonError (ctx , internalServerError )
55
40
}
56
41
}()
57
42
handler (ctx )
@@ -62,7 +47,7 @@ func WithJson[T any](handler func(ctx *gin.Context) (T, error)) func(ctx *gin.Co
62
47
return WithRecover ("WithJson panic" , func (ctx * gin.Context ) {
63
48
data , err := handler (ctx )
64
49
if err != nil {
65
- AbortWithJsonError (ctx , http . StatusBadRequest , err )
50
+ AbortWithJsonError (ctx , err )
66
51
} else {
67
52
ctx .JSON (200 , DataResponse [T ]{
68
53
Success : true ,
@@ -76,7 +61,7 @@ func WithText(handler func(ctx *gin.Context) (string, error)) func(ctx *gin.Cont
76
61
return WithRecover ("WithText panic" , func (ctx * gin.Context ) {
77
62
data , err := handler (ctx )
78
63
if err != nil {
79
- AbortWithJsonError (ctx , http . StatusBadRequest , err )
64
+ AbortWithJsonError (ctx , err )
80
65
} else {
81
66
ctx .String (200 , data )
82
67
}
0 commit comments