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,
}
}
- 定义错误码
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实战】 获取完整代码
🛒 站长推荐(京东联盟)
- 《Go 程序设计语言》(Go 语言圣经,机械工业出版社) —— Go 官方团队出品,公认入门第一书
- 《Go 语言实战》(异步图书,人民邮电出版社) —— 实战导向,面试前巩固工程手感
- 《Go 语言编程之旅:一起用 Go 做项目》(博文视点,电子工业出版社) —— 项目驱动入门,从零写出完整应用
- Keychron K1Max 矮轴机械键盘(Mac/Win 双系统,QMK/VIA 开源改键) —— 轻薄矮轴 + 开源固件,程序员桌面常客
- 罗技 MX Master 3S 无线鼠标(Flow 跨屏,静音电磁滚轮) —— 人体工学设计,写代码一整天手不酸
以上链接含京东联盟推广代码;通过链接购买本站可能获得少量佣金,不影响你的购买价格。
📮 关注公众号「GO语言入门之路」
每周更新 Go + AI 应用开发实战:AI 面试官完整项目、MCP、Agent 工程化,完整源码随文章首发。
微信扫码,或搜索「GO语言入门之路」关注,第一时间获取系列更新与源码,不再错过任何一篇。