Guides
Guides

Error Handling

You can use Golf.Error to set handlers for different type of errors like the following:

App.Error(401, unauthorizedHandler)
App.Error(404, notFoundHandler)

To raise an error inside context, please use the method Context.Abort:

func homeHandler(ctx *golf.Context) {
  user, e := getUser()
  if e != nil {
    ctx.Abort(401)
    return
  }
  ctx.Loader("template").Render("index.html", data)
}

🚧

Warning

Please notice that a return must be called after ctx.Abort, otherwise the rest part of the request handler will still be executed.

Golf will find the corresponding error handler in the error handler map. If the error handler for this status code is not set, golf calls App.DefaultErrorHandler.

You can also indicate a DefaultErrorHandler manually.

func NotFoundHandler(ctx *golf.Context, data ...map[string]interface{}) {
  ctx.Loader("templates").Render("error.html", data)
}

App.DefaultErrorHandler = errorHandler