Dragonfly2

Форк
0
128 строк · 3.0 Кб
1
/*
2
 *     Copyright 2020 The Dragonfly Authors
3
 *
4
 * Licensed under the Apache License, Version 2.0 (the "License");
5
 * you may not use this file except in compliance with the License.
6
 * You may obtain a copy of the License at
7
 *
8
 *      http://www.apache.org/licenses/LICENSE-2.0
9
 *
10
 * Unless required by applicable law or agreed to in writing, software
11
 * distributed under the License is distributed on an "AS IS" BASIS,
12
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13
 * See the License for the specific language governing permissions and
14
 * limitations under the License.
15
 */
16

17
package middlewares
18

19
import (
20
	"errors"
21
	"net/http"
22

23
	"github.com/VividCortex/mysqlerr"
24
	"github.com/gin-gonic/gin"
25
	"github.com/go-redis/redis/v8"
26
	"github.com/go-sql-driver/mysql"
27
	redigo "github.com/gomodule/redigo/redis"
28
	"golang.org/x/crypto/bcrypt"
29
	"gorm.io/gorm"
30

31
	commonv1 "d7y.io/api/v2/pkg/apis/common/v1"
32

33
	"d7y.io/dragonfly/v2/internal/dferrors"
34
)
35

36
type ErrorResponse struct {
37
	Message     string `json:"message,omitempty"`
38
	Error       string `json:"errors,omitempty"`
39
	DocumentURL string `json:"documentation_url,omitempty"`
40
}
41

42
func Error() gin.HandlerFunc {
43
	return func(c *gin.Context) {
44
		c.Next()
45
		err := c.Errors.Last()
46
		if err == nil {
47
			return
48
		}
49

50
		// Redigo error handler
51
		if errors.Is(err, redigo.ErrNil) {
52
			c.JSON(http.StatusNotFound, ErrorResponse{
53
				Message: http.StatusText(http.StatusNotFound),
54
			})
55
			c.Abort()
56
			return
57
		}
58

59
		// RPC error handler
60
		var dferr *dferrors.DfError
61
		if errors.As(err.Err, &dferr) {
62
			switch dferr.Code {
63
			case commonv1.Code_InvalidResourceType:
64
				c.JSON(http.StatusBadRequest, ErrorResponse{
65
					Message: http.StatusText(http.StatusBadRequest),
66
				})
67
				c.Abort()
68
				return
69
			default:
70
				c.JSON(http.StatusInternalServerError, ErrorResponse{
71
					Message: http.StatusText(http.StatusInternalServerError),
72
				})
73
				c.Abort()
74
				return
75
			}
76
		}
77

78
		// Bcrypt error handler
79
		if errors.Is(err, bcrypt.ErrMismatchedHashAndPassword) {
80
			c.JSON(http.StatusUnauthorized, ErrorResponse{
81
				Message: http.StatusText(http.StatusUnauthorized),
82
			})
83
			c.Abort()
84
			return
85
		}
86

87
		// GORM error handler
88
		if errors.Is(err.Err, gorm.ErrRecordNotFound) {
89
			c.JSON(http.StatusNotFound, ErrorResponse{
90
				Message: http.StatusText(http.StatusNotFound),
91
			})
92
			c.Abort()
93
			return
94
		}
95

96
		// Mysql error handler
97
		var merr *mysql.MySQLError
98
		if errors.As(err.Err, &merr) {
99
			switch merr.Number {
100
			case mysqlerr.ER_DUP_ENTRY:
101
				c.JSON(http.StatusConflict, ErrorResponse{
102
					Message: http.StatusText(http.StatusConflict),
103
				})
104
				c.Abort()
105
				return
106
			default:
107
				c.JSON(http.StatusInternalServerError, ErrorResponse{
108
					Message: http.StatusText(http.StatusInternalServerError),
109
				})
110
				c.Abort()
111
				return
112
			}
113
		}
114

115
		if errors.Is(err.Err, redis.Nil) {
116
			c.JSON(http.StatusNotFound, ErrorResponse{
117
				Message: http.StatusText(http.StatusNotFound),
118
			})
119
			c.Abort()
120
			return
121
		}
122

123
		// Unknown error
124
		c.JSON(http.StatusInternalServerError, ErrorResponse{
125
			Message: err.Err.Error(),
126
		})
127
	}
128
}
129

Использование cookies

Мы используем файлы cookie в соответствии с Политикой конфиденциальности и Политикой использования cookies.

Нажимая кнопку «Принимаю», Вы даете АО «СберТех» согласие на обработку Ваших персональных данных в целях совершенствования нашего веб-сайта и Сервиса GitVerse, а также повышения удобства их использования.

Запретить использование cookies Вы можете самостоятельно в настройках Вашего браузера.