Buffalo中需在templates/error/下创建404.plush.html和500.plush.html,启用Renderer中间件,并重启服务生效;不支持其他路径或扩展名,且必须使用Plush语法。

在Buffalo框架中为Web应用添加符合业务风格的404页面和500错误提示页,是上线前必须完成的基础配置。默认错误页简陋且暴露技术栈,直接面向用户会降低信任感,还可能被扫描工具识别出框架版本。
确认项目使用模板引擎
Buffalo仅在启用模板引擎(如Plush、HTML)时才支持自定义error页面。若项目用--api创建且未手动添加templates/目录,则此方案不适用——需先执行buffalo generate template error/404.html并确保render中间件已启用。
检查app.go中是否存在app.Use(middleware.Renderer)或类似调用;若无,后续所有页面文件将被忽略。
创建标准错误页面文件
Buffalo遵循约定优于配置原则,错误页必须放在templates/error/目录下,且文件名严格匹配状态码数字:
在终端中执行:mkdir -p templates/error → touch templates/error/404.plush.html templates/error/500.plush.html
这一步不可跳过,【Buffalo不会自动创建error目录,也不接受其他路径或扩展名】。若放错位置(如templates/404.html),请求仍返回默认白屏错误页。
编写可复用的错误页内容
方法一:基础Plush模板(推荐新手)
编辑templates/error/404.plush.html,写入:
<html><body><h1>抱歉,您访问的页面不存在</h1><p>错误代码:404</p></body></html>
Buffalo框架 1.0.1 版本源码包下载,适合需要错误处理改进、依赖更新、render.Download 注释和 request logger 调整的 v1 项目。
方法二:复用布局(适合已有_application.plush.html)
在templates/error/404.plush.html中写:
<%= partial("layouts/_application.plush.html", {title: "页面未找到", content: content}) %>
然后在layouts/_application.plush.html里用<%= content %>插入主体。这样能统一头部、CSS和脚部,避免每个错误页重复写结构。
注意:Plush模板中不能使用Go原生html/template语法,否则编译报错。
强制刷新错误页渲染逻辑
Buffalo在开发模式下不会实时监听templates/error/目录变更。完成编辑后必须执行以下任一操作:
① 重启开发服务器:buffalo dev → Ctrl+C终止 → 再次运行
② 清除缓存并重载:buffalo task clear → buffalo dev
若跳过此步,浏览器仍显示旧版错误页或空白内容。生产环境构建时(buffalo build),模板会被打包进二进制,无需额外操作。

















