saasitone/pkg/handlers/error.go

55 lines
1.2 KiB
Go
Raw Permalink Normal View History

package handlers
2021-12-03 03:11:01 -08:00
import (
"net/http"
"github.com/labstack/echo/v4"
2024-07-09 17:57:05 -07:00
"git.grosinger.net/tgrosinger/saasitone/pkg/context"
"git.grosinger.net/tgrosinger/saasitone/pkg/log"
"git.grosinger.net/tgrosinger/saasitone/pkg/page"
"git.grosinger.net/tgrosinger/saasitone/pkg/services"
2024-07-17 17:33:50 -07:00
"git.grosinger.net/tgrosinger/saasitone/templ/layouts"
"git.grosinger.net/tgrosinger/saasitone/templ/pages"
2021-12-03 03:11:01 -08:00
)
type Error struct {
*services.TemplateRenderer
2021-12-03 03:11:01 -08:00
}
func (e *Error) Page(err error, ctx echo.Context) {
if ctx.Response().Committed || context.IsCanceledError(err) {
2021-12-11 16:32:27 -08:00
return
}
// Determine the error status code
2021-12-03 03:11:01 -08:00
code := http.StatusInternalServerError
if he, ok := err.(*echo.HTTPError); ok {
code = he.Code
}
// Log the error
logger := log.Ctx(ctx)
switch {
case code >= 500:
logger.Error(err.Error())
case code >= 400:
logger.Warn(err.Error())
2021-12-03 03:11:01 -08:00
}
// Render the error page
p := page.New(ctx)
p.Title = http.StatusText(code)
p.StatusCode = code
p.LayoutComponent = layouts.Main
p.HTMX.Request.Enabled = false
2024-07-17 17:33:50 -07:00
component := pages.Error(p)
if err = e.RenderPageTempl(ctx, p, component); err != nil {
log.Ctx(ctx).Error("failed to render error page",
"error", err,
)
2021-12-03 03:11:01 -08:00
}
}