54 lines
934 B
Go
54 lines
934 B
Go
package models
|
|
|
|
import (
|
|
"fmt"
|
|
"net/http"
|
|
)
|
|
|
|
type HTTPError struct {
|
|
Code int `json:"code"`
|
|
Message string `json:"message"`
|
|
Data any `json:"data"`
|
|
}
|
|
|
|
func NewHTTPError(code int) *HTTPError {
|
|
return &HTTPError{
|
|
Code: code,
|
|
Message: http.StatusText(code),
|
|
}
|
|
}
|
|
|
|
func ParseHTTPError(err error) *HTTPError {
|
|
if err == nil {
|
|
return nil
|
|
}
|
|
|
|
if httpErr, ok := err.(*HTTPError); ok {
|
|
return httpErr
|
|
}
|
|
|
|
return NewHTTPError(http.StatusInternalServerError).SetMessage(err.Error())
|
|
}
|
|
|
|
func IsHTTPError(err error) bool {
|
|
_, ok := err.(*HTTPError)
|
|
return ok
|
|
}
|
|
|
|
func (e *HTTPError) Error() string {
|
|
return e.Message
|
|
}
|
|
|
|
func (err *HTTPError) String() string {
|
|
return fmt.Sprintf("[ERROR] %d: %s, Data: %+v", err.Code, err.Message, err.Data)
|
|
}
|
|
|
|
func (err *HTTPError) Is(code int) bool {
|
|
return err.Code == code
|
|
}
|
|
|
|
func (err *HTTPError) SetMessage(message string) *HTTPError {
|
|
err.Message = message
|
|
return err
|
|
}
|