trepa/internal/core/errors.go
2025-03-11 21:42:36 +00:00

52 lines
997 B
Go

package core
import (
"encoding/json"
"net/http"
)
var (
ErrInvalidToken = NewHTTPError(http.StatusUnauthorized, "Invalid token", nil)
ErrInvalidStruct = NewHTTPError(http.StatusBadRequest, "Invalid struct", nil)
)
type HTTPError struct {
Code int `json:"code"`
Message string `json:"message"`
Cause error `json:"-"`
Details string `json:"details,omitempty"`
}
func (e *HTTPError) Error() string {
return e.Message
}
func (e *HTTPError) Unwrap() error {
return e.Cause
}
func (e *HTTPError) IntoJsonBytes() []byte {
json, err := json.Marshal(e)
if err != nil {
return nil
}
return json
}
func NewHTTPError(code int, message string, cause error) *HTTPError {
details := ""
if cause != nil {
details = cause.Error()
}
return &HTTPError{
Code: code,
Message: message,
Cause: cause,
Details: details,
}
}
func NewInternalServerError(cause error) *HTTPError {
return NewHTTPError(http.StatusInternalServerError, "Internal server error", cause)
}