gin error如何返回结果
📅 2026/7/31 18:16:23
👁️ 阅读次数
📝 编程学习
在 Gin 中处理错误并返回结果,常见有以下几种方式:
1. 直接返回 JSON 错误(最简单)
go
func GetUser(c *gin.Context) { user, err := db.FindUser(id) if err != nil { c.JSON(http.StatusInternalServerError, gin.H{ "code": 500, "msg": "查询用户失败", "data": nil, }) return // 注意必须 return,防止继续执行 } c.JSON(http.StatusOK, gin.H{ "code": 0, "msg": "success", "data": user, }) }2. 使用AbortWithStatusJSON(推荐用于中间件或需终止后续处理时)
go
if !isAuthorized { c.AbortWithStatusJSON(http.StatusUnauthorized, gin.H{ "code": 401, "msg": "未授权", }) return }与c.JSON的区别:AbortWithStatusJSON会设置c.Abort(),阻止后续中间件/Handler 执行。
3. 统一错误响应结构体(项目规范做法)
go
type Response struct { Code int `json:"code"` Msg string `json:"msg"` Data interface{} `json:"data"` } func Error(c *gin.Context, code int, msg string) { c.JSON(code, Response{Code: code, Msg: msg, Data: nil}) } func Success(c *gin.Context, data interface{}) { c.JSON(http.StatusOK, Response{Code: 0, Msg: "success", Data: data}) } // 使用 func Handler(c *gin.Context) { if err := doSomething(); err != nil { Error(c, 500, err.Error()) return } Success(c, result) }4. 全局错误恢复中间件
go
func RecoveryMiddleware() gin.HandlerFunc { return func(c *gin.Context) { defer func() { if err := recover(); err != nil { c.JSON(http.StatusInternalServerError, gin.H{ "code": 500, "msg": "服务器内部错误", }) } }() c.Next() } } // 注册 r.Use(RecoveryMiddleware())关键注意点
表格
| 要点 | 说明 |
|---|---|
必须return | 调用c.JSON后如果不return,后续代码会继续执行 |
| 状态码 | 建议 HTTP status 与业务 code 分开,HTTP 用标准码,业务 code 放 body |
| Abort | 鉴权类错误用AbortWithStatusJSON,普通业务错误用c.JSON即可 |
你目前是在写具体的 Handler 逻辑,还是想搭建一套全局的错误处理机制?可以帮你进一步细化。
编程学习
技术分享
实战经验