如何在Buffalo中统一处理应用错误并返回自定义错误页面

解读

国内一线/二线互联网公司面试 Buffalo 相关岗位时,这道题出现的频率极高。
面试官真正想验证的不仅是“能不能改个 HTML”,而是:

  1. 你是否理解 Buffalo 的“中间件-错误处理链”执行顺序;
  2. 你是否能把业务错误码、日志、监控、前端友好页面一次性打通;
  3. 你是否知道生产环境要把堆栈信息隔离,避免敏感信息泄露;
  4. 你是否具备“可插拔”思维:当项目从 Buffalo 迁出或 Buffalo 版本升级时,错误处理层改动最小。

一句话:这道题考察的是“全栈意识 + 安全意识 + 工程化能力”。

知识点

  1. ErrorHandlingMiddlware 执行点:在路由匹配之后、响应写出之前, buffalo.DefaultErrorHandler 会被调用。
  2. buffalo.ErrorHandler 接口签名:func (status int, err error, c buffalo.Context) error。
  3. buffalo.Context 提供 Set/Render,可重写响应状态码、响应头、响应体。
  4. buffalo.App#ErrorHandlers 映射表:key 是 HTTP 状态码,value 是自定义的 ErrorHandler。
  5. HTML、JSON、XML 多格式协商:通过 c.Request().Header.Get("Accept") 判断,同一套错误处理函数可返回不同表现形式,方便前后端分离。
  6. 日志联动:使用 c.Logger().WithField("error", err).Error(...) 写入结构化日志,接入 ELK / Loki。
  7. 安全合规:
    • 生产环境禁止把 err.Error() 直接暴露给前端;
    • 5xx 页面只返回统一提示,内部用 UUID 关联日志;
    • 4xx 页面可返回细化文案,但仍需脱敏。
  8. 热重载友好:把错误模板放在 templates/_errors/ 目录,Buffalo 开发模式下自动监听变动,无需重启。
  9. 测试策略:
    • 单元测试用 httptest.NewRecorder() 直接调用 app.ErrorHandlers[404](404, errors.New("mock"), c);
    • 集成测试用 wsf.Test 发起真实 HTTP 请求,断言返回体是否包含约定错误码。
  10. 版本差异:Buffalo v0.x 与 v1.x 在 ErrorHandlers 初始化时机略有不同,v1.x 要求 app.ErrorHandlers 在 app.Serve() 之前完成注册,否则会被默认 handler 覆盖。

答案

(以下代码基于 Buffalo v1.1.0,Go 1.20,生产验证可直接落地)

步骤 1:定义错误响应 DTO,统一前后端字段

type ErrResp struct {
    Code    string `json:"code"`              // 业务错误码,如 BIZ_404
    Message string `json:"message"`           // 用户可读描述
    TraceID string `json:"trace_id"`          // 链路追踪 ID
}

步骤 2:编写可复用的错误处理函数

func customErrorHandler(status int, origErr error, c buffalo.Context) error {
    // 1. 生成追踪 ID,便于日志索引
    tid := c.Value("trace_id").(string)
    if tid == "" {
        tid = shortid.MustGenerate()
    }

    // 2. 记录完整堆栈到后端日志,生产环境不开源详情
    c.Logger().WithFields(logrus.Fields{
        "status":   status,
        "error":    origErr.Error(),
        "trace_id": tid,
    }).Error("buffalo unified error")

    // 3. 根据 Accept 头决定返回格式
    accept := c.Request().Header.Get("Accept")
    isJSON := strings.Contains(accept, "application/json")
    isXML  := strings.Contains(accept, "application/xml")

    // 4. 构造安全脱敏的对外信息
    resp := ErrResp{
        Code:    fmt.Sprintf("BIZ_%d", status),
        TraceID: tid,
    }
    switch {
    case status >= 500:
        resp.Message = "服务器开小差了,请稍后重试"
    case status == 404:
        resp.Message = "您访问的页面不存在"
    default:
        resp.Message = http.StatusText(status)
    }

    // 5. 写出响应
    c.Response().WriteHeader(status)
    if isJSON {
        return c.Render(status, r.JSON(resp))
    }
    if isXML {
        return c.Render(status, r.XML(resp))
    }
    // 默认 HTML 错误页
    c.Set("error", resp)
    return c.Render(status, r.HTML("_errors/%d.plush.html", status))
}

步骤 3:在 app.go 的 App() 构建函数中注册

app := buffalo.New(buffalo.Options{
    Env:         ENV,
    SessionName: "_buffalo_session",
})

// 覆盖默认 handler
app.ErrorHandlers[404] = customErrorHandler
app.ErrorHandlers[500] = customErrorHandler
// 也可以一次性覆盖所有
for code := 400; code <= 599; code++ {
    app.ErrorHandlers[code] = customErrorHandler
}

步骤 4:放置模板
templates/_errors/404.plush.html
templates/_errors/500.plush.html
使用 plush 语法即可拿到 <%= error.Message %> 与 <%= error.TraceID %>。

步骤 5:验证

# 开发模式
buffalo dev
curl -H "Accept: application/json" http://localhost:3000/notfound
# 返回 {"code":"BIZ_404","message":"您访问的页面不存在","trace_id":"xxx"}

# HTML 页面直接在浏览器打开 /notfound 即可看到自定义 404 页面

步骤 6:上线 checklist

  • 关闭 buffalo.DefaultErrorHandler 的调试模式:ENV=production buffalo build
  • 在 CI 中跑 go test -tags integration ./actions 确保错误码断言通过
  • 在 Nginx 层也配置 50x 静态页,作为最后一道防线,防止 Buffalo 进程整体挂掉时用户看到默认 Nginx 错误页。

拓展思考

  1. 微服务场景:把 customErrorHandler 抽到独立仓库,以 plugin 形式注入,各业务 Buffalo 网关只需 import 即可保持错误格式一致,方便统一监控大盘。
  2. 错误码升级:当业务需要“错误码可翻译”时,可在 ErrResp 里再加 i18n.Key 字段,利用 Buffalo 自带的 i18n.Bundle,在 customErrorHandler 里根据 c.Value("lang") 动态渲染多语言页面。
  3. 性能优化:错误处理函数里不要每次都 shortid.MustGenerate(),可提前用 sync.Pool 缓存对象;高并发接口 4xx 比例升高时,避免日志打爆磁盘,可以采样记录(如 1/100)。
  4. 安全攻防:自定义 404 页面里不要出现“路由存在但参数错误”之类的提示,否则攻击者可利用差异响应做目录爆破;统一返回 200 + 业务错误码是更安全的做法。
  5. 平滑迁移:如果未来要把 Buffalo 换成 Gin 或 Echo,只需保证错误响应 DTO 与 trace_id 生成规则不变,前端和监控侧无需改动,真正做到“框架可替换,错误协议不变”。