博客
关于我
beego自定义404、401、403、500、503等页面
阅读量:657 次
发布时间:2019-03-15

本文共 1240 字,大约阅读时间需要 4 分钟。

Beego框架内置了对常见HTTP错误状态码(如404、401、403、500、503)的错误处理功能。开发者可以根据需要自定义相应的错误页面显示内容,从1.4.3版本开始,支持通过Controller方式定义错误处理方法。

要实现自定义错误处理,可按以下步骤完成配置:

  • 首先,在你的应用的main.go文件中添加Beego的错误控制器配置。只需在main函数中添加如下代码即可:
  • beego.ErrorController(&controllers.ErrorController{})
    1. 创建相应的错误处理控制器。新建一个名为ErrorController的控制器类,放在controllers包中。该控制器需要实现诸多处理错误的方法,具体如下:
    2. type ErrorController struct {    beego.Controller}func (c *ErrorController) Error401() {    c.Data["content"] = "未经授权,请求要求验证身份"    c.TplName = "error/401.tpl"}func (c *ErrorController) Error403() {    c.Data["content"] = "服务器拒绝请求"    c.TplName = "error/403.tpl"}func (c *ErrorController) Error404() {    c.Data["content"] = "很抱歉您访问的地址或者方法不存在"    c.TplName = "error/404.tpl"}func (c *ErrorController) Error500() {    c.Data["content"] = "server error"    c.TplName = "error/500.tpl"}func (c *ErrorController) Error503() {    c.Data["content"] = "服务器目前无法使用(由于超载或停机维护)"    c.TplName = "error/503.tpl"}
      1. 创建相应的错误模板文件。将error目录添加到views中,每个错误类型对应一个*.tpl模板文件。例如,404错误页面可以在view/error/404.tpl中定义,内容大致如下:
      2.     
        404

        {[content]}

        @template_dc params={.content, .title}
        1. 在浏览器中访问您的Beego应用,测试各类错误页面是否正确显示。例如,访问一个不存在的路由地址,观察系统是否自动跳转至对应的404错误页面。
        2. 完成以上配置步骤后,您的Beego应用将能够根据不同HTTP错误状态 返回自定义的显示页面,既美观又符合业务需求。

    转载地址:http://dqvmz.baihongyu.com/

    你可能感兴趣的文章
    npm install 报错 EEXIST File exists 的解决方法
    查看>>
    npm install 报错 ERR_SOCKET_TIMEOUT 的解决方法
    查看>>
    npm install 报错 Failed to connect to github.com port 443 的解决方法
    查看>>
    npm install 报错 fatal: unable to connect to github.com 的解决方法
    查看>>
    npm install 报错 no such file or directory 的解决方法
    查看>>
    npm install 权限问题
    查看>>
    npm install报错,证书验证失败unable to get local issuer certificate
    查看>>
    npm install无法生成node_modules的解决方法
    查看>>
    npm install的--save和--save-dev使用说明
    查看>>
    npm node pm2相关问题
    查看>>
    npm run build 失败Compiler server unexpectedly exited with code: null and signal: SIGBUS
    查看>>
    npm run build报Cannot find module错误的解决方法
    查看>>
    npm run build部署到云服务器中的Nginx(图文配置)
    查看>>
    npm run dev 和npm dev、npm run start和npm start、npm run serve和npm serve等的区别
    查看>>
    npm run dev 报错PS ‘vite‘ 不是内部或外部命令,也不是可运行的程序或批处理文件。
    查看>>
    npm scripts 使用指南
    查看>>
    npm should be run outside of the node repl, in your normal shell
    查看>>
    npm start运行了什么
    查看>>
    npm WARN deprecated core-js@2.6.12 core-js@<3.3 is no longer maintained and not recommended for usa
    查看>>
    npm 下载依赖慢的解决方案(亲测有效)
    查看>>