Gin实战8:实现错误处理和统一格式返回


🌟 导语

在我们之前的文章中,我们主要讲解了Gin框架的搭建以及业务流程的实现。但是其中对错误处理和接口响应格式没有很好的处理。因此,本篇文章将介绍如何实现统一格式的响应,并实现统一错误处理。

一、设计通用响应结构体

统一返回 状态码 + 提示语 + 业务数据 等字段

type Response struct {
	Code      int         `json:"code"`
	Data      interface{} `json:"data"`
	Msg       string      `json:"msg"`
	Timestamp int64       `json:"timestamp"`
}

封装统一的数据响应方法,用于service层统一返回数据

  • 返回正常数据
func Success(ctx *gin.Context, data interface{}) {
	ctx.JSON(http.StatusOK, Response{
		Code:      errorcode.Success,
		Data:      data,
		Timestamp: time.Now().Unix(),
		Msg:       "success",
	})
}
  • 返回错误数据
func Error(ctx *gin.Context, err error) {
	if err == nil {
		err = errorcode.ErrServerError
	}
	ctx.JSON(http.StatusOK, Response{
		Code: err.(*errorcode.GinError).Code(),
		Msg:  err.Error(),
		Data: struct {
		}{},
		Timestamp: time.Now().Unix(),
	})
}

二、自定义错误类型体系

1.创建GinError结构体

type GinError struct {
	code int    `json:"code"`
	msg  string `json:"msg"`
}

func (e *GinError) Error() string {
	return fmt.Sprintf("code:%d,msg:%s", e.code, e.msg)
}

func (e *GinError) Code() int {
	return e.code
}

func NewGinError(code int, msg string) *GinError {
	return &GinError{
		code: code,
		msg:  msg,
	}
}
  1. 定义错误码

const (
	Success = 200
	// ErrInternalServerError represents a 500 status code.
	ErrInternalServerErrorCode = 500
	// ErrBadRequest represents a 400 status code.
	ErrBadRequestCode = 400
	// ErrUnauthorized represents a 401 status code.
	ErrUnauthorizedCode = 401
	// ErrForbidden represents a 403 status code.
	ErrForbiddenCode = 403
	// ErrNotFound represents a 404 status code.
	ErrNotFoundCode = 404
	// ErrConflict represents a 409 status code.
	ErrConflictCode = 409
)

var (
	ErrServerError    = NewGinError(ErrInternalServerErrorCode, "Internal Server Error")
	ErrBadRequest     = NewGinError(ErrBadRequestCode, "Bad Request")
	ErrUnauthorized   = NewGinError(ErrUnauthorizedCode, "Unauthorized")
	ErrForbidden      = NewGinError(ErrForbiddenCode, "Forbidden")
	ErrNotFound       = NewGinError(ErrNotFoundCode, "Not Found")
	ErrConflict       = NewGinError(ErrConflictCode, "Conflict")
	ErrInvalidRequest = NewGinError(ErrBadRequestCode, "Invalid Request")
)

三、错误处理

  • Data 层 错误记录日志 并返回错误
  • Biz 层 错误返回错误
  • Service 层 返回统一错误码和错误信息
    err := ctx.ShouldBind(&req)
	if err != nil {
		response.Error(ctx, errorcode.ErrBadRequest)
		return
	}
	if req.Username == "" || req.Password == "" {
		response.Error(ctx, errorcode.NewGinError(errorcode.ErrBadRequestCode, "username or password is empty"))
		return
	}

感谢你的关注和支持,回复【Gin实战】 获取完整代码

wx

关注公众号

©2017-2023 鲁ICP备17023316号-1 Powered by Hugo