Files
mtusi2026lab2/app/internal/common/error.go
T

123 lines
3.0 KiB
Go

package common
import (
"errors"
"github.com/gofiber/fiber/v3"
)
const (
ErrorCodeInvalidRequest = "invalid_request"
ErrorCodeUnauthorized = "unauthorized"
ErrorCodeNotFound = "not_found"
ErrorCodeConflict = "conflict"
ErrorCodePayloadTooLarge = "payload_too_large"
ErrorCodeUnsupportedMedia = "unsupported_media_type"
ErrorCodeRateLimited = "rate_limited"
ErrorCodeUnavailable = "unavailable"
ErrorCodeInternal = "internal_error"
)
type APIErrorResponse struct {
Error APIError `json:"error"`
}
type APIError struct {
Code string `json:"code"`
Message string `json:"message"`
RequestID string `json:"request_id"`
}
func NewError(code, message, requestID string) APIErrorResponse {
return APIErrorResponse{
Error: APIError{
Code: code,
Message: message,
RequestID: requestID,
},
}
}
type AppError struct {
Status int
Code string
Message string
}
func (e *AppError) Error() string {
return e.Message
}
func NewAppError(status int, code, message string) *AppError {
return &AppError{
Status: status,
Code: code,
Message: message,
}
}
func BadRequest(message string) *AppError {
return NewAppError(fiber.StatusBadRequest, ErrorCodeInvalidRequest, message)
}
func Unauthorized(message string) *AppError {
return NewAppError(fiber.StatusUnauthorized, ErrorCodeUnauthorized, message)
}
func NotFound(message string) *AppError {
return NewAppError(fiber.StatusNotFound, ErrorCodeNotFound, message)
}
func Conflict(message string) *AppError {
return NewAppError(fiber.StatusConflict, ErrorCodeConflict, message)
}
func UnsupportedMedia(message string) *AppError {
return NewAppError(fiber.StatusUnsupportedMediaType, ErrorCodeUnsupportedMedia, message)
}
func Internal() *AppError {
return NewAppError(fiber.StatusInternalServerError, ErrorCodeInternal, "Internal server error")
}
func ErrorCodeFromStatus(status int) string {
switch status {
case fiber.StatusBadRequest:
return ErrorCodeInvalidRequest
case fiber.StatusUnauthorized:
return ErrorCodeUnauthorized
case fiber.StatusNotFound:
return ErrorCodeNotFound
case fiber.StatusConflict:
return ErrorCodeConflict
case fiber.StatusRequestEntityTooLarge:
return ErrorCodePayloadTooLarge
case fiber.StatusUnsupportedMediaType:
return ErrorCodeUnsupportedMedia
case fiber.StatusTooManyRequests:
return ErrorCodeRateLimited
case fiber.StatusServiceUnavailable:
return ErrorCodeUnavailable
default:
return ErrorCodeInternal
}
}
func getRequestID(c fiber.Ctx) string {
return string(c.Response().Header.Peek("X-Request-Id"))
}
func SendError(c fiber.Ctx, status int, code, message string) error {
return c.Status(status).JSON(NewError(code, message, getRequestID(c)))
}
func SendAppError(c fiber.Ctx, err error) error {
var appErr *AppError
if errors.As(err, &appErr) {
return SendError(c, appErr.Status, appErr.Code, appErr.Message)
}
return SendError(c, fiber.StatusInternalServerError,
ErrorCodeInternal, "Internal server error")
}