-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy patherror_lib.go
52 lines (45 loc) · 1.03 KB
/
error_lib.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
package ginboot
import (
"errors"
"fmt"
"github.com/gin-gonic/gin"
"net/http"
)
type ApiError struct {
ErrorCode string `json:"error_code"`
Message string `json:"message"`
}
func (e ApiError) New(messages ...string) ApiError {
args := make([]any, len(messages))
for i, msg := range messages {
args[i] = msg
}
message := fmt.Sprintf(e.Message, args...)
return ApiError{
ErrorCode: e.ErrorCode,
Message: message,
}
}
func (e ApiError) Error() string {
return fmt.Sprintf("%s: %s", e.ErrorCode, e.Message)
}
type ErrorResponse struct {
ErrorCode string `json:"error_code"`
Message string `json:"message"`
}
func SendError(c *gin.Context, err error) {
var customErr ApiError
if errors.As(err, &customErr) {
c.JSON(http.StatusBadRequest, gin.H{
"error_code": customErr.ErrorCode,
"message": customErr.Message,
})
return
}
// Handle other types of errors here
c.JSON(http.StatusInternalServerError, gin.H{
"error_code": "Internal Server Error",
"message": "An unknown error occurred",
})
return
}