Error Handling

When we do web development, we often need page jumping and error handling, and Beego has taken this into account, using the Redirect method for redirecting:

  1. func (this *AddController) Get() {
  2. this.Redirect("/", 302)
  3. }

To abort the request and throw an exception, Beego can do this in the controller:

  1. func (this *MainController) Get() {
  2. this.Abort("401")
  3. v := this.GetSession("asta")
  4. if v == nil {
  5. this.SetSession("asta", int(1))
  6. this.Data["Email"] = 0
  7. } else {
  8. this.SetSession("asta", v.(int)+1)
  9. this.Data["Email"] = v.(int)
  10. }
  11. this.TplName = "index.tpl"
  12. }

So that the code after this.Abort("401") will not be executed and the following page will be displayed to the user by default:

Error Handling - 图1

The web framework supports 401, 403, 404, 500, 503 error handling by default. Users can customize the corresponding error handling, for example, the following redefines the 404 page:

  1. func page_not_found(rw http.ResponseWriter, r *http.Request){
  2. t,_:= template.New("404.html").ParseFiles(web.BConfig.WebConfig.ViewsPath+"/404.html")
  3. data :=make(map[string]interface{})
  4. data["content"] = "page not found"
  5. t.Execute(rw, data)
  6. }
  7. func main() {
  8. web.ErrorHandler("404",page_not_found)
  9. web.Router("/", &controllers.MainController{})
  10. web.Run()
  11. }

We can handle 404 errors by customizing the error page 404.html.

Another more user-friendly aspect of Beego is its support for user-defined string error type handling functions, such as the following code, where the user registers a database error handling page:

  1. func dbError(rw http.ResponseWriter, r *http.Request){
  2. t,_:= template.New("dberror.html").ParseFiles(web.BConfig.WebConfig.ViewsPath+"/dberror.html")
  3. data :=make(map[string]interface{})
  4. data["content"] = "database is now down"
  5. t.Execute(rw, data)
  6. }
  7. func main() {
  8. web.ErrorHandler("dbError",dbError)
  9. web.Router("/", &controllers.MainController{})
  10. web.Run()
  11. }

Once you register this error handling code in the entry, then you can call this.Abort("dbError") for exception page handling whenever you encounter a database error in your logic.

Controller define Error

Beego version 1.4.3 added support for Controller defined Error handlers, so we can use the web.Controller and template.Render context functions

  1. package controllers
  2. import (
  3. "github.com/beego/beego/v2/server/web"
  4. )
  5. type ErrorController struct {
  6. web.Controller
  7. }
  8. func (c *ErrorController) Error404() {
  9. c.Data["content"] = "page not found"
  10. c.TplName = "404.tpl"
  11. }
  12. func (c *ErrorController) Error500() {
  13. c.Data["content"] = "internal server error"
  14. c.TplName = "500.tpl"
  15. }
  16. func (c *ErrorController) ErrorDb() {
  17. c.Data["content"] = "database is now down"
  18. c.TplName = "dberror.tpl"
  19. }

From the example we can see that all the error handling functions have the prefix Error,the other string is the name of Abort,like Error404 match Abort("404")

Use web.ErrorController to register the error controller before web.Run

  1. package main
  2. import (
  3. _ "btest/routers"
  4. "btest/controllers"
  5. "github.com/beego/beego/v2/server/web"
  6. )
  7. func main() {
  8. web.ErrorController(&controllers.ErrorController{})
  9. web.Run()
  10. }

Panic Handling

If you want the user to be able to return a response even if a panic occurs while the server is processing the request, then you can use Beego’s recovery mechanism. This mechanism is enabled by default.

  1. web.BConfig.RecoverPanic = true

If you want to customize the processing behavior after panic, then you can reset web.BConfig.RecoverFunc:

  1. web.BConfig.RecoverFunc = func(context *context.Context, config *web.Config) {
  2. if err := recover(); err != nil {
  3. context.WriteString(fmt.Sprintf("you panic, err: %v", err))
  4. }
  5. }

Always be careful: you always need to detect the result of recover and put the logic for recovering from panic inside the code that detects that recover does not return nil.

Reference

-Controller API - Interrupt