iris中需通过panic包裹bizerror或用stopwithstatus+json组合实现统一错误响应,因框架不自动拦截controller返回的error;同时可注册errorhandler中间件捕获状态码异常并注入biz_error值。

在Iris框架中使用MVC架构时,需要将控制器中抛出的业务错误、校验失败、数据库异常等统一转换为标准HTTP响应格式,避免每个方法里重复写ctx.StatusCode()和ctx.JSON()。
定义统一错误结构体
新建zerr/errors.go文件,声明业务错误类型:
type BizError struct { Code int `json:"code"` Msg string `json:"msg"` Data interface{} `json:"data,omitempty"` }
func (e *BizError) Error() string { return fmt.Sprintf("[%d]%s", e.Code, e.Msg) }
这一步必须做,否则后续panic恢复或中间件无法识别业务错误类型。Iris的mvc层不自动捕获panic以外的error返回值,【所有controller方法返回error都不会被框架拦截】。
注册全局错误处理器
在main函数中,于app.Listen()之前插入:
app.Use(func(ctx iris.Context) { defer func() { if r := recover(); r != nil { ctx.StatusCode(500) ctx.JSON(BizError{Code: 50001, Msg: "系统异常,请稍后重试"}) } }() ctx.Next() })
注意:仅靠recover只能捕获panic,不能捕获return的error。所以必须配合下一步手动触发。
在Controller中主动抛出BizError
方法一:用panic包裹BizError(最简路径)
func (c *UserController) GetByID(id int64) string { if id
方法二:用ctx.StopWithStatus() + ctx.JSON()组合(推荐)
func (c *UserController) GetByID(id int64) { if id
【StopWithStatus必须紧跟JSON之后且带return,否则后续逻辑仍会执行】。Iris不会自动中断controller方法执行流。
用BeforeActivation注入错误中间件
第一步:定义错误处理中间件
func ErrorHandler(ctx iris.Context) { ctx.Next() if ctx.Response.StatusCode() >= 400 && ctx.Response.StatusCode()
第二步:在Controller中注册该中间件
func (c *UserController) BeforeActivation(b mvc.BeforeActivation) { b.Router().Use(ErrorHandler) }
第三步:在controller方法内设置错误值
func (c *UserController) GetByID(id int64) { if id











