錯誤處理器可以讓你記錄錯誤和格式化錯誤響應(HTML、JSON、XML…),其接收一個 Context 實例和一個由中間件或者最終處理器產生的錯誤

    1. type ErrorHandler struct {
    2. tmpl *template.Template
    3. }
    4. func NewErrorHandler(tmpl *template.Template) *ErrorHandler {
    5. return &ErrorHandler{
    6. tmpl: tmpl,
    7. }
    8. }
    9. func (h *ErrorHandler) Handle(ctx *clevergo.Context, err error) {
    10. // write error to log.
    11. log.Println(err)
    12. format := ctx.DefaultQuery("format", "html")
    13. switch format {
    14. case "json":
    15. ctx.JSON(http.StatusOK, map[string]interface{}{
    16. "message": err.Error(),
    17. })
    18. default:
    19. h.tmpl.Execute(ctx.Response, err)
    20. }
    21. }
    22. tmpl := template.Must(template.New("error").Parse(`<html><body><h1>{{ .Error }}</h1></body></html>`))
    23. router.ErrorHandler = NewErrorHandler(tmpl)
    1. $ curl http://localhost:8080/404
    2. <html><body><h1>404 page not found</h1></body></html>
    3. $ curl "http://localhost:8080/404?format=json"
    4. {"message":"404 page not found"}