aboutsummaryrefslogtreecommitdiff
path: root/pkg/handler/error.go
blob: 821a3f3b0d2de0af4e4fb5e5f65b59d5770413ca (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
package handler

import (
	"log"
	"net/http"

	"github.com/labstack/echo/v4"
	"neonxp.ru/go/framework/pkg/tpl"
)

func ErrorHandler(err error, c echo.Context) {
	if c.Response().Committed {
		return
	}

	he, ok := err.(*echo.HTTPError)
	if ok {
		if he.Internal != nil {
			if herr, ok := he.Internal.(*echo.HTTPError); ok {
				he = herr
			}
		}
	} else {
		he = &echo.HTTPError{
			Code:    http.StatusInternalServerError,
			Message: http.StatusText(http.StatusInternalServerError),
		}
	}
	code := he.Code
	message, ok := he.Message.(string)
	if !ok {
		message = "Неизвестная ошибка"
	}

	if c.Request().Method == http.MethodHead {
		err = c.NoContent(he.Code)
	} else {
		c.Response().WriteHeader(code)
		if err := tpl.ErrorPage(code, message).
			Render(c.Request().Context(), c.Response()); err != nil {
			log.Println(err)
		}
	}
	if err != nil {
		log.Println(err)
	}
}