Documentation
¶
Overview ¶
Package xerrors provides a structured error handling mechanism for HTTP applications.
It extends the standard Go error interface by embedding HTTP status codes, application-specific string codes, and error chaining (cause) capabilities. This allows handlers to return rich errors that the global error handler can automatically translate into correct HTTP responses.
Basic usage:
if err != nil {
return xerrors.Wrap(err, "DB_ERROR", "failed to query user", 500)
}
if user == nil {
return xerrors.New("USER_NOT_FOUND", "user does not exist", 404)
}
Index ¶
- Constants
- Variables
- func As(err error, target interface{}) bool
- func GetCode(err error) string
- func GetFields(err error) map[string]any
- func HTTPStatusCode(err error) int
- func Is(err, target error) bool
- func Join(errs ...error) error
- func New(code, message string, httpStatus int) error
- func NewWithFields(code, message string, httpStatus int, fields map[string]any) error
- func StackTraceString(err error) string
- func Wrap(err error, code, message string, httpStatus int) error
- func WrapWithFields(err error, code, message string, httpStatus int, fields map[string]any) error
- type CustomError
- type Frame
Constants ¶
const ( StatusOK = 200 StatusCreated = 201 StatusAccepted = 202 StatusNoContent = 204 StatusBadRequest = 400 StatusForbidden = 403 StatusNotFound = 404 StatusMethodNotAllowed = 405 StatusNotAcceptable = 406 StatusRequestTimeout = 408 StatusConflict = 409 StatusPayloadTooLarge = 413 StatusUnsupportedMedia = 415 StatusUnprocessableEntity = 422 StatusTooManyRequests = 429 StatusInternalServerError = 500 StatusNotImplemented = 501 StatusBadGateway = 502 StatusGatewayTimeout = 504 )
Standard HTTP status codes, mapped from net/http for convenience without importing it
Variables ¶
var ( // 4xx Client Errors ErrBadRequest = New("BAD_REQUEST", "Invalid request parameters", StatusBadRequest) ErrInvalidToken = New("INVALID_TOKEN", "Token is invalid or expired", StatusUnauthorized) ErrForbidden = New("FORBIDDEN", "You do not have permission to access this resource", StatusForbidden) ErrNotFound = New("NOT_FOUND", "Resource not found", StatusNotFound) ErrMethodNotAllowed = New("METHOD_NOT_ALLOWED", "HTTP method not allowed for this resource", StatusMethodNotAllowed) ErrNotAcceptable = New("NOT_ACCEPTABLE", "Requested format is not supported", StatusNotAcceptable) ErrRequestTimeout = New("REQUEST_TIMEOUT", "Request took too long to process", StatusRequestTimeout) ErrConflict = New("CONFLICT", "Resource already exists or conflict occurred", StatusConflict) ErrPayloadTooLarge = New("PAYLOAD_TOO_LARGE", "Request payload exceeds the maximum allowed size", StatusPayloadTooLarge) ErrUnsupportedMedia = New("UNSUPPORTED_MEDIA_TYPE", "Media type is not supported", StatusUnsupportedMedia) ErrUnprocessableEntity = New("UNPROCESSABLE_ENTITY", "Data validation failed", StatusUnprocessableEntity) ErrTooManyRequests = New("TOO_MANY_REQUESTS", "Rate limit exceeded, please try again later", StatusTooManyRequests) // 5xx Server Errors ErrInternal = New("INTERNAL_ERROR", "An unexpected internal error occurred", StatusInternalServerError) ErrNotImplemented = New("NOT_IMPLEMENTED", "This feature is not yet implemented", StatusNotImplemented) ErrBadGateway = New("BAD_GATEWAY", "Invalid response from upstream server", StatusBadGateway) ErrGatewayTimeout = New("GATEWAY_TIMEOUT", "Upstream server timed out", StatusGatewayTimeout) )
Common error variables that can be reused across services.
They are shared sentinels: match them with errors.Is (which compares Code) and never modify their fields. Their stack trace was captured at package init, so it does not point at the call site. To get a useful stack, return xerrors.Wrap(err, ...) or xerrors.New(...) instead of the sentinel itself.
Functions ¶
func GetFields ¶
GetFields extracts the structured fields map from an error. Returns nil if the error is not a *CustomError.
func HTTPStatusCode ¶
HTTPStatusCode extracts the HTTP status code from an error. If it's a CustomError, it returns its status. Otherwise, 500.
func NewWithFields ¶
NewWithFields creates a new CustomError with structured context fields.
Example:
return xerrors.NewWithFields("USER_NOT_FOUND", "user not found", 404,
map[string]any{"user_id": id})
func StackTraceString ¶
StackTraceString formats the stack trace as a human-readable multi-line string. Returns "" if no stack is captured.
Types ¶
type CustomError ¶
type CustomError struct {
Code string
Message string
HTTPStatus int
Cause error
Fields map[string]any // structured context (e.g. {"user_id": "123"})
// contains filtered or unexported fields
}
CustomError represents a standard application error with optional stack trace.
func (*CustomError) Error ¶
func (e *CustomError) Error() string
Error implements the standard error interface.
func (*CustomError) Is ¶
func (e *CustomError) Is(target error) bool
Is makes errors.Is match any *CustomError with the same Code, so errors.Is(Wrap(err, "NOT_FOUND", ...), ErrNotFound) is true.
func (*CustomError) StackTrace ¶
func (e *CustomError) StackTrace() []Frame
StackTrace returns the captured call stack frames, filtering out runtime internals.
func (*CustomError) Unwrap ¶
func (e *CustomError) Unwrap() error
Unwrap implements the interface for errors.Is and errors.As.