go-urlsh/internal/misc/error.go

44 lines
1 KiB
Go
Raw Permalink Normal View History

2024-05-04 17:06:01 +02:00
package misc
import (
2024-05-06 13:11:46 +02:00
"encoding/json"
"errors"
2024-05-06 13:11:46 +02:00
"code.lila.network/adoralaura/go-urlsh/models"
"github.com/gofiber/fiber/v2"
)
func HandleError(c *fiber.Ctx, err error) error {
code := fiber.StatusInternalServerError
// Retrieve the custom status code if it's a *fiber.Error
var e *fiber.Error
if errors.As(err, &e) {
code = e.Code
}
// Set Content-Type: text/plain; charset=utf-8
c.Set(fiber.HeaderContentType, fiber.MIMETextPlainCharsetUTF8)
// Return status code with error message
return c.Status(code).SendString(err.Error())
}
2024-05-04 17:06:01 +02:00
func New500Error() error {
return fiber.NewError(fiber.StatusInternalServerError, "500 Internal Server Error")
}
func New400Error() error {
return fiber.NewError(fiber.StatusBadRequest, "400 Bad Request")
}
2024-05-06 13:11:46 +02:00
func New400WithMessageError(msg string) error {
body, _ := json.Marshal(models.HttpErrorBody{Message: msg})
return fiber.NewError(fiber.StatusBadRequest, string(body[:]))
}
2024-05-04 17:06:01 +02:00
func New401Error() error {
return fiber.NewError(fiber.StatusUnauthorized, "401 Unauthorized")
}