Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

refactor: 重构错误处理和日志记录 #6

Merged
merged 1 commit into from
Oct 31, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
82 changes: 51 additions & 31 deletions app/apiException/apiException.go
Original file line number Diff line number Diff line change
@@ -1,50 +1,70 @@
package apiException

import "net/http"
import (
"net/http"

// Error 表示自定义错误,包括状态码、代码和消息。
"4u-go/app/utils/log"
"github.com/gin-gonic/gin"
"go.uber.org/zap"
)

// Error 表示自定义错误,包括状态码、消息和日志级别。
type Error struct {
StatusCode int `json:"-"`
Code int `json:"code"`
Msg string `json:"msg"`
Code int
Msg string
Level log.Level
}

// Error 表示自定义的错误类型
var (
ServerError = NewError(http.StatusInternalServerError, 200500, "系统异常,请稍后重试!")
OpenIDError = NewError(http.StatusInternalServerError, 200500, "系统异常,请稍后重试!")
ParamError = NewError(http.StatusInternalServerError, 200501, "参数错误")
ReactiveError = NewError(http.StatusInternalServerError, 200502, "该通行证已经存在,请重新输入")
UserAlreadyExisted = NewError(http.StatusInternalServerError, 200503, "该用户已激活")
RequestError = NewError(http.StatusInternalServerError, 200504, "系统异常,请稍后重试!")
StudentNumAndIidError = NewError(http.StatusInternalServerError, 200505, "该学号或身份证不存在或者不匹配,请重新输入")
PwdError = NewError(http.StatusInternalServerError, 200506, "密码长度必须在6~20位之间")
UserNotFound = NewError(http.StatusInternalServerError, 200507, "该用户不存在")
NoThatPasswordOrWrong = NewError(http.StatusInternalServerError, 200508, "密码错误")
NotLogin = NewError(http.StatusInternalServerError, 200509, "未登录")
NotPermission = NewError(http.StatusInternalServerError, 200510, "该用户无权限")
ActivityNotFound = NewError(http.StatusInternalServerError, 200511, "活动不存在")

NotInit = NewError(http.StatusNotFound, 200404, http.StatusText(http.StatusNotFound))
NotFound = NewError(http.StatusNotFound, 200404, http.StatusText(http.StatusNotFound))
Unknown = NewError(http.StatusInternalServerError, 300500, "系统异常,请稍后重试!")
)
ServerError = NewError(200500, log.LevelError, "系统异常,请稍后重试!")
OpenIDError = NewError(200500, log.LevelInfo, "系统异常,请稍后重试!")
ParamError = NewError(200501, log.LevelInfo, "参数错误")
ReactiveError = NewError(200502, log.LevelInfo, "该通行证已经存在,请重新输入")
UserAlreadyExisted = NewError(200503, log.LevelInfo, "该用户已激活")
RequestError = NewError(200504, log.LevelInfo, "系统异常,请稍后重试!")
StudentNumAndIidError = NewError(200505, log.LevelInfo, "该学号或身份证不存在或者不匹配,请重新输入")
PwdError = NewError(200506, log.LevelInfo, "密码长度必须在6~20位之间")
UserNotFound = NewError(200507, log.LevelInfo, "该用户不存在")
NoThatPasswordOrWrong = NewError(200508, log.LevelInfo, "密码错误")
NotLogin = NewError(200509, log.LevelInfo, "未登录")
NotPermission = NewError(200510, log.LevelInfo, "该用户无权限")
ActivityNotFound = NewError(200511, log.LevelInfo, "活动不存在")

// OtherError 返回一个表示其他未定义错误的自定义错误消息
func OtherError(message string) *Error {
return NewError(http.StatusForbidden, 100403, message)
}
NotInit = NewError(200404, log.LevelWarn, http.StatusText(http.StatusNotFound))
NotFound = NewError(200404, log.LevelWarn, http.StatusText(http.StatusNotFound))
Unknown = NewError(300500, log.LevelError, "系统异常,请稍后重试!")
)

// Error 方法实现了 error 接口,返回错误的消息内容
func (e *Error) Error() string {
return e.Msg
}

// NewError 创建并返回一个新的自定义错误实例
func NewError(statusCode, code int, msg string) *Error {
func NewError(code int, level log.Level, msg string) *Error {
return &Error{
StatusCode: statusCode,
Code: code,
Msg: msg,
Code: code,
Msg: msg,
Level: level,
}
}

// AbortWithException 用于返回自定义错误信息
func AbortWithException(c *gin.Context, apiError *Error, err error) {
logError(c, apiError, err)
_ = c.AbortWithError(200, apiError) //nolint:errcheck
}

// logError 记录错误日志
func logError(c *gin.Context, apiErr *Error, err error) {
// 构建日志字段
logFields := []zap.Field{
zap.Int("error_code", apiErr.Code),
zap.String("path", c.Request.URL.Path),
zap.String("method", c.Request.Method),
zap.String("ip", c.ClientIP()),
zap.Error(err), // 记录原始错误信息
}
log.GetLogFunc(apiErr.Level)(apiErr.Msg, logFields...)
}
8 changes: 4 additions & 4 deletions app/controllers/activityController/create.go
Original file line number Diff line number Diff line change
Expand Up @@ -27,19 +27,19 @@ func CreateActivity(c *gin.Context) {
var data createActivityData
err := c.ShouldBindJSON(&data)
if err != nil {
utils.JsonErrorResponse(c, apiException.ParamError, utils.LevelInfo, err)
apiException.AbortWithException(c, apiException.ParamError, err)
return
}

// 转换时间
startTime, err := time.Parse(time.RFC3339, data.StartTime)
if err != nil {
utils.JsonErrorResponse(c, apiException.ParamError, utils.LevelInfo, err)
apiException.AbortWithException(c, apiException.ParamError, err)
return
}
endTime, err := time.Parse(time.RFC3339, data.EndTime)
if err != nil {
utils.JsonErrorResponse(c, apiException.ParamError, utils.LevelInfo, err)
apiException.AbortWithException(c, apiException.ParamError, err)
return
}

Expand All @@ -55,7 +55,7 @@ func CreateActivity(c *gin.Context) {
AuthorID: c.GetUint("user_id"),
})
if err != nil {
utils.JsonErrorResponse(c, apiException.ServerError, utils.LevelError, err)
apiException.AbortWithException(c, apiException.ServerError, err)
return
}

Expand Down
10 changes: 5 additions & 5 deletions app/controllers/activityController/delete.go
Original file line number Diff line number Diff line change
Expand Up @@ -17,31 +17,31 @@ func DeleteActivity(c *gin.Context) {
var data deleteActivityData
err := c.ShouldBindJSON(&data)
if err != nil {
utils.JsonErrorResponse(c, apiException.ParamError, utils.LevelInfo, err)
apiException.AbortWithException(c, apiException.ParamError, err)
return
}

// 判断活动是否存在
activity, err := activityService.GetActivityById(data.ID)
if err != nil {
if err == gorm.ErrRecordNotFound {
utils.JsonErrorResponse(c, apiException.ActivityNotFound, utils.LevelInfo, err)
apiException.AbortWithException(c, apiException.ActivityNotFound, err)
} else {
utils.JsonErrorResponse(c, apiException.ServerError, utils.LevelError, err)
apiException.AbortWithException(c, apiException.ServerError, err)
}
return
}

user := c.GetUint("user_id")
adminType := c.GetUint("admin_type")
if activity.AuthorID != user && adminType != 4 {
utils.JsonErrorResponse(c, apiException.NotPermission, utils.LevelInfo, nil)
apiException.AbortWithException(c, apiException.NotPermission, nil)
return
}

err = activityService.DeleteActivityById(data.ID)
if err != nil {
utils.JsonErrorResponse(c, apiException.ServerError, utils.LevelError, err)
apiException.AbortWithException(c, apiException.ServerError, err)
return
}

Expand Down
6 changes: 3 additions & 3 deletions app/controllers/activityController/get.go
Original file line number Diff line number Diff line change
Expand Up @@ -38,19 +38,19 @@ func GetActivityList(c *gin.Context) {
var data getActivityData
err := c.ShouldBindJSON(&data)
if err != nil {
utils.JsonErrorResponse(c, apiException.ParamError, utils.LevelInfo, err)
apiException.AbortWithException(c, apiException.ParamError, err)
return
}

user, err := sessionService.GetUserSession(c)
if err != nil {
utils.JsonErrorResponse(c, apiException.NotLogin, utils.LevelInfo, err)
apiException.AbortWithException(c, apiException.NotLogin, err)
return
}

list, err := activityService.GetActivityList(data.Campus)
if err != nil {
utils.JsonErrorResponse(c, apiException.ServerError, utils.LevelError, err)
apiException.AbortWithException(c, apiException.ServerError, err)
return
}

Expand Down
14 changes: 7 additions & 7 deletions app/controllers/activityController/update.go
Original file line number Diff line number Diff line change
Expand Up @@ -29,36 +29,36 @@ func UpdateActivity(c *gin.Context) {
var data updateActivityData
err := c.ShouldBindJSON(&data)
if err != nil {
utils.JsonErrorResponse(c, apiException.ParamError, utils.LevelInfo, err)
apiException.AbortWithException(c, apiException.ParamError, err)
return
}

// 转换时间
startTime, err := time.Parse(time.RFC3339, data.StartTime)
if err != nil {
utils.JsonErrorResponse(c, apiException.ParamError, utils.LevelInfo, err)
apiException.AbortWithException(c, apiException.ParamError, err)
return
}
endTime, err := time.Parse(time.RFC3339, data.EndTime)
if err != nil {
utils.JsonErrorResponse(c, apiException.ParamError, utils.LevelInfo, err)
apiException.AbortWithException(c, apiException.ParamError, err)
return
}

activity, err := activityService.GetActivityById(data.ID)
if errors.Is(err, gorm.ErrRecordNotFound) {
utils.JsonErrorResponse(c, apiException.ActivityNotFound, utils.LevelInfo, err)
apiException.AbortWithException(c, apiException.ActivityNotFound, err)
return
}
if err != nil {
utils.JsonErrorResponse(c, apiException.ServerError, utils.LevelError, err)
apiException.AbortWithException(c, apiException.ServerError, err)
return
}

user := c.GetUint("user_id")
adminType := c.GetUint("admin_type")
if activity.AuthorID != user && adminType != 4 {
utils.JsonErrorResponse(c, apiException.NotPermission, utils.LevelInfo, nil)
apiException.AbortWithException(c, apiException.NotPermission, nil)
return
}

Expand All @@ -75,7 +75,7 @@ func UpdateActivity(c *gin.Context) {

err = activityService.SaveActivity(activity)
if err != nil {
utils.JsonErrorResponse(c, apiException.ServerError, utils.LevelError, err)
apiException.AbortWithException(c, apiException.ServerError, err)
return
}

Expand Down
25 changes: 12 additions & 13 deletions app/controllers/userController/auth.go
Original file line number Diff line number Diff line change
Expand Up @@ -22,33 +22,33 @@ func AuthByPassword(c *gin.Context) {
var postForm passwordLoginForm
err := c.ShouldBindJSON(&postForm)
if err != nil {
utils.JsonErrorResponse(c, apiException.ParamError, utils.LevelInfo, err)
apiException.AbortWithException(c, apiException.ParamError, err)
return
}

user, err := userService.GetUserByStudentID(postForm.StudentID)
if errors.Is(err, gorm.ErrRecordNotFound) {
utils.JsonErrorResponse(c, apiException.UserNotFound, utils.LevelInfo, err)
apiException.AbortWithException(c, apiException.UserNotFound, err)
return
}
if err != nil {
utils.JsonErrorResponse(c, apiException.ServerError, utils.LevelInfo, err)
apiException.AbortWithException(c, apiException.ServerError, err)
return
}

if err := userService.AuthenticateUser(user, postForm.Password); err != nil {
var apiErr *apiException.Error
if errors.As(err, &apiErr) {
utils.JsonErrorResponse(c, apiErr, utils.LevelInfo, err)
apiException.AbortWithException(c, apiErr, err)
} else {
utils.JsonErrorResponse(c, apiException.ServerError, utils.LevelError, err)
apiException.AbortWithException(c, apiException.ServerError, err)
}
return
}

err = sessionService.SetUserSession(c, user)
if err != nil {
utils.JsonErrorResponse(c, apiException.ServerError, utils.LevelError, err)
apiException.AbortWithException(c, apiException.ServerError, err)
return
}
utils.JsonSuccessResponse(c, gin.H{
Expand All @@ -70,7 +70,7 @@ type autoLoginForm struct {
func AuthBySession(c *gin.Context) {
user, err := sessionService.UpdateUserSession(c)
if err != nil {
utils.JsonErrorResponse(c, apiException.ServerError, utils.LevelError, err)
apiException.AbortWithException(c, apiException.ServerError, err)
return
}
utils.JsonSuccessResponse(c, gin.H{
Expand All @@ -89,29 +89,28 @@ func WeChatLogin(c *gin.Context) {
var postForm autoLoginForm
err := c.ShouldBindJSON(&postForm)
if err != nil {
utils.JsonErrorResponse(c, apiException.ParamError, utils.LevelInfo, err)
apiException.AbortWithException(c, apiException.ParamError, err)
return
}

session, err := wechat.MiniProgram.GetAuth().Code2Session(postForm.Code)
if err != nil {
utils.JsonErrorResponse(c, apiException.OpenIDError, utils.LevelError, err)
apiException.AbortWithException(c, apiException.OpenIDError, err)
return
}

user, err := userService.GetUserByWechatOpenID(session.OpenID)
if errors.Is(err, gorm.ErrRecordNotFound) {
utils.JsonErrorResponse(c, apiException.UserNotFound, utils.LevelInfo, err)
apiException.AbortWithException(c, apiException.UserNotFound, err)
return
} else if err != nil {
utils.JsonErrorResponse(c, apiException.ServerError, utils.LevelError, err)
apiException.AbortWithException(c, apiException.ServerError, err)
return
}

err = sessionService.SetUserSession(c, user)
if err != nil {
utils.JsonErrorResponse(c, apiException.ServerError, utils.LevelError, err)

apiException.AbortWithException(c, apiException.ServerError, err)
return
}
utils.JsonSuccessResponse(c, gin.H{
Expand Down
18 changes: 9 additions & 9 deletions app/controllers/userController/reg.go
Original file line number Diff line number Diff line change
Expand Up @@ -26,12 +26,12 @@ func BindOrCreateStudentUserFromWechat(c *gin.Context) {
var postForm createStudentUserWechatForm
err := c.ShouldBindJSON(&postForm)
if err != nil {
utils.JsonErrorResponse(c, apiException.ParamError, utils.LevelInfo, err)
apiException.AbortWithException(c, apiException.ParamError, err)
return
}
session, err := wechat.MiniProgram.GetAuth().Code2Session(postForm.Code)
if err != nil {
utils.JsonErrorResponse(c, apiException.OpenIDError, utils.LevelInfo, err)
apiException.AbortWithException(c, apiException.OpenIDError, err)
return
}
postForm.StudentID = strings.ToUpper(postForm.StudentID)
Expand All @@ -46,16 +46,16 @@ func BindOrCreateStudentUserFromWechat(c *gin.Context) {
if err != nil {
var apiErr *apiException.Error
if errors.As(err, &apiErr) {
utils.JsonErrorResponse(c, apiErr, utils.LevelInfo, err)
apiException.AbortWithException(c, apiErr, err)
} else {
utils.JsonErrorResponse(c, apiException.ServerError, utils.LevelInfo, err)
apiException.AbortWithException(c, apiException.ServerError, err)
}
return
}

err = sessionService.SetUserSession(c, user)
if err != nil {
utils.JsonErrorResponse(c, apiException.ServerError, utils.LevelInfo, err)
apiException.AbortWithException(c, apiException.ServerError, err)
return
}
utils.JsonSuccessResponse(c, nil)
Expand All @@ -74,7 +74,7 @@ func CreateStudentUser(c *gin.Context) {
var postForm createStudentUserForm
err := c.ShouldBindJSON(&postForm)
if err != nil {
utils.JsonErrorResponse(c, apiException.ParamError, utils.LevelInfo, err)
apiException.AbortWithException(c, apiException.ParamError, err)
return
}
postForm.StudentID = strings.ToUpper(postForm.StudentID)
Expand All @@ -88,16 +88,16 @@ func CreateStudentUser(c *gin.Context) {
if err != nil {
var apiErr *apiException.Error
if errors.As(err, &apiErr) {
utils.JsonErrorResponse(c, apiErr, utils.LevelInfo, err)
apiException.AbortWithException(c, apiErr, err)
} else {
utils.JsonErrorResponse(c, apiException.ServerError, utils.LevelError, err)
apiException.AbortWithException(c, apiException.ServerError, err)
}
return
}

err = sessionService.SetUserSession(c, user)
if err != nil {
utils.JsonErrorResponse(c, apiException.ServerError, utils.LevelError, err)
apiException.AbortWithException(c, apiException.ServerError, err)
return
}
utils.JsonSuccessResponse(c, nil)
Expand Down
Loading