-
Notifications
You must be signed in to change notification settings - Fork 0
/
error-handler.go
107 lines (91 loc) · 2.06 KB
/
error-handler.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
97
98
99
100
101
102
103
104
105
106
107
package util
import (
"errors"
"fmt"
"github.com/gin-gonic/gin"
"github.com/go-sql-driver/mysql"
"github.com/jmoiron/sqlx"
"net/http"
"runtime/debug"
"strings"
)
type HttpError struct {
StatusCode int
Message string
}
func (err HttpError) Error() string {
return fmt.Sprintf("http error %d: %s", err.StatusCode, err.Message)
}
func BadRequest(message ...interface{}) error {
return HttpError{
StatusCode: http.StatusBadRequest,
Message: fmt.Sprintln(message...),
}
}
func PanicBadRequest(message ...interface{}) {
panic(BadRequest(message...))
}
func InternalServerError(message ...interface{}) error {
return HttpError{
StatusCode: http.StatusInternalServerError,
Message: fmt.Sprintln(message...),
}
}
func PanicInternalServerError(message ...interface{}) {
panic(InternalServerError(message...))
}
func NewHttpError(code int, message ...interface{}) error {
return HttpError{
StatusCode: code,
Message: fmt.Sprintln(message...),
}
}
func PanicHttp(code int, message ...interface{}) {
panic(NewHttpError(code, message...))
}
func HandleErrors(c *gin.Context) {
if r := recover(); r != nil {
err := r.(error)
if httpErr, ok := err.(HttpError); ok {
c.JSON(httpErr.StatusCode, gin.H{
"data": httpErr.Message,
})
return
}
// ignored errors:
if strings.Contains(err.Error(), "An established connection was aborted by the software in your host machine") {
return
}
fmt.Println(err)
debug.PrintStack()
if _, ok := err.(*mysql.MySQLError); ok {
c.JSON(http.StatusInternalServerError, gin.H{
"data": "Error while executing on database",
})
return
}
c.JSON(http.StatusInternalServerError, gin.H{
"data": "Internal error",
})
return
}
}
func HandleUpdaterErrors() {
if r := recover(); r != nil {
err, ok := r.(error)
if !ok {
err = errors.New(r.(string))
}
fmt.Println(err)
debug.PrintStack()
return
}
}
func Rollback(tx *sqlx.Tx) { // defer rollback
if r := recover(); r != nil {
_ = tx.Rollback()
panic(r) // fall back to default error handling
} else {
_ = tx.Commit()
}
}