delphi.market/server/error.go

50 lines
1.1 KiB
Go
Raw Normal View History

package server
import (
2024-07-10 06:20:04 +00:00
"bytes"
"net/http"
2023-11-26 17:21:26 +00:00
"strings"
2024-07-10 06:20:04 +00:00
"git.ekzyis.com/ekzyis/delphi.market/server/router/context"
"git.ekzyis.com/ekzyis/delphi.market/server/router/pages"
"github.com/a-h/templ"
"github.com/labstack/echo/v4"
)
2024-07-10 06:20:04 +00:00
func httpErrorHandler(sc context.Context) echo.HTTPErrorHandler {
return func(err error, c echo.Context) {
var (
code = http.StatusInternalServerError
page = pages.Error
buf *bytes.Buffer
)
c.Logger().Error(err)
if httpError, ok := err.(*echo.HTTPError); ok {
code = httpError.Code
}
if strings.Contains(err.Error(), "violates check constraint") ||
strings.Contains(err.Error(), "violates unique constraint") {
code = 400
}
buf = templ.GetBuffer()
defer templ.ReleaseBuffer(buf)
if err = page(code).Render(context.RenderContext(sc, c), buf); err != nil {
c.Logger().Error(err)
code = http.StatusInternalServerError
}
2024-07-15 04:16:46 +00:00
// make sure that HTMX selects and targets correct element
c.Response().Header().Add("HX-Retarget", "#content")
c.Response().Header().Add("HX-Reselect", "#content")
2024-07-10 06:20:04 +00:00
if err = c.HTML(code, buf.String()); err != nil {
c.Logger().Error(err)
}
}
}