44 lines
949 B
Go
44 lines
949 B
Go
|
|
package middleware
|
||
|
|
|
||
|
|
import (
|
||
|
|
"net/http"
|
||
|
|
|
||
|
|
"github.com/gin-gonic/gin"
|
||
|
|
|
||
|
|
apierrors "github.com/user-management-system/internal/pkg/errors"
|
||
|
|
)
|
||
|
|
|
||
|
|
// ErrorHandler 错误处理中间件
|
||
|
|
func ErrorHandler() gin.HandlerFunc {
|
||
|
|
return func(c *gin.Context) {
|
||
|
|
c.Next()
|
||
|
|
|
||
|
|
// 检查是否有错误
|
||
|
|
if len(c.Errors) > 0 {
|
||
|
|
// 获取最后一个错误
|
||
|
|
err := c.Errors.Last()
|
||
|
|
|
||
|
|
// 判断错误类型
|
||
|
|
if appErr, ok := err.Err.(*apierrors.ApplicationError); ok {
|
||
|
|
c.JSON(int(appErr.Code), appErr)
|
||
|
|
} else {
|
||
|
|
c.JSON(http.StatusInternalServerError, apierrors.New(http.StatusInternalServerError, "", err.Err.Error()))
|
||
|
|
}
|
||
|
|
return
|
||
|
|
}
|
||
|
|
}
|
||
|
|
}
|
||
|
|
|
||
|
|
// Recover 恢复中间件
|
||
|
|
func Recover() gin.HandlerFunc {
|
||
|
|
return func(c *gin.Context) {
|
||
|
|
defer func() {
|
||
|
|
if err := recover(); err != nil {
|
||
|
|
c.JSON(http.StatusInternalServerError, apierrors.New(http.StatusInternalServerError, "", "服务器内部错误"))
|
||
|
|
c.Abort()
|
||
|
|
}
|
||
|
|
}()
|
||
|
|
c.Next()
|
||
|
|
}
|
||
|
|
}
|