Implement any-error handler

pull/1/head
Nikita Tokarchuk 3 years ago
parent f0b3d34c05
commit a04066148f
Signed by: mainnika
GPG Key ID: A595FB7E3E56911C
  1. 40
      frontend/renderer/error.go
  2. 1
      frontend/renderer/renderer.go

@ -1,8 +1,12 @@
package renderer
import (
"fmt"
"net/http"
"code.tokarch.uk/mainnika/nikita-tokarch-uk/frontend/content"
routing "github.com/jackwhelpton/fasthttp-routing/v2"
"github.com/sirupsen/logrus"
)
// errorNotFound renders http error-404 template
@ -12,3 +16,39 @@ func (r *Renderer) errorNotFound(c *routing.Context) (err error) {
return c.Write(errorContent)
}
// useErrorHandler is the middleware that catch handlers errors and render error template
func (r *Renderer) useErrorHandler(c *routing.Context) (err error) {
worker := func() (err error) {
defer func() {
r := recover()
if r == nil {
return
}
err = routing.NewHTTPError(http.StatusInternalServerError,
fmt.Sprintf("panic:\n%v", r))
}()
err = c.Next()
return
}
err = worker()
if err == nil {
return
}
c.Abort()
logrus.Warnf("Cannot process request, %v", err)
errorContent := content.Error{
Message: err.Error(),
}
return c.Write(errorContent)
}

@ -29,6 +29,7 @@ func (r *Renderer) init() {
router := routing.New()
router.Use(r.useTemplateWriter)
router.Use(r.useErrorHandler)
router.NotFound(r.errorNotFound)
r.router = router

Loading…
Cancel
Save