beego 错误处理

【beego 错误处理】参考网站

https://beego.me/docs/mvc/controller/errors.md

在做 Web 开发的时候,经常需要页面跳转和错误处理,beego 这方面也进行了考虑,通过 Redirect 方法来进行跳转
func (this *InfoController) Get() { this.Redirect("Info.html", 302) // 跳转到指定页面 }

如何中止此次请求并抛出异常, this.Abort(“401”) 之后的代码不会再执行,而且会显示默认页面
func (this *UserInfoController) Get() { this.Abort("401") v := this.GetSession("Name") if v == nil { this.SetSession("Name", int(1)) this.Data["Email"] = 0 } else { this.SetSession("Name", v.(int)+1) this.Data["Email"] = v.(int) } this.TplName = "index.tpl" }

Controller 方式定义 Error 错误处理函数
package controllersimport ( "github.com/astaxie/beego" )type ErrorController struct { beego.Controller }func (c *ErrorController) Error404() { c.Data["content"] = "page not found" c.TplName = "404.tpl" }func (c *ErrorController) Error501() { c.Data["content"] = "server error" c.TplName = "501.tpl" }func (c *ErrorController) ErrorDb() { c.Data["content"] = "database is now down" c.TplName = "dberror.tpl" }

所有的函数都是有一定规律的,都是 Error 开头,后面的名字就是我们调用 Abort 的名字,例如 Error404 函数其实调用对应的就是 Abort(“404”) 我们就只要在 beego.Run 之前采用 beego.ErrorController 注册这个错误处理函数就可以了
package mainimport ( _ "btest/routers" "btest/controllers""github.com/astaxie/beego" )func main() { beego.ErrorController(&controllers.ErrorController{}) beego.Run() }

    推荐阅读