aboutsummaryrefslogblamecommitdiff
path: root/pkg/handler/error.go
blob: eac791def2d0d000622e93edbc8504cca19238bb (plain) (tree)














































                                                                                 
package handler

import (
	"log"
	"net/http"

	"github.com/labstack/echo/v4"
	"go.neonxp.ru/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)
	}
}