From b9c5b3e0e0b423762bee876656f36a25e7b57738 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Sebastian=20D=C3=B6ll?= Date: Thu, 12 Sep 2024 07:41:03 +0000 Subject: [PATCH] feat: add error handler for toasts --- components/toasts/errors.go | 33 +++++++++++++++++++++++++++++++++ 1 file changed, 33 insertions(+) create mode 100644 components/toasts/errors.go diff --git a/components/toasts/errors.go b/components/toasts/errors.go new file mode 100644 index 0000000..6ea8a02 --- /dev/null +++ b/components/toasts/errors.go @@ -0,0 +1,33 @@ +package toasts + +import ( + "errors" + + "github.com/gofiber/fiber/v2" + htmx "github.com/zeiss/fiber-htmx" +) + +// DefaultErrorHandler is the default error handler for toasts. +var DefaultErrorHandler = func(c *fiber.Ctx, err error) error { + code := fiber.StatusInternalServerError + + var te Toast + if !errors.As(err, &te) { + te = Error("there has been an unexpected error") + } + + if te.Level != SUCCESS { + htmx.ReSwap(c, "none") + } + + te.SetHXTriggerHeader(c) + + var e *fiber.Error + if errors.As(err, &e) { + code = e.Code + } + + c.Set(fiber.HeaderContentType, fiber.MIMETextPlainCharsetUTF8) + + return c.Status(code).SendString(err.Error()) +}