Error Handling (core/errors)
github.com/mmycin/goforge/core/errors defines a canonical AppError type used across middleware, handlers, validation, and services.
AppError JSON Contract
go
type AppError struct {
HTTPStatus int `json:"-"`
Code string `json:"code"`
Message string `json:"message"`
Details any `json:"details,omitempty"`
cause error
}Example HTTP response (422):
json
{
"code": "UNPROCESSABLE_ENTITY",
"message": "validation failed",
"details": [
{ "field": "title", "message": "title is a required field" }
]
}Methods on *AppError:
Error() string/Unwrap() error(compatible witherrors.Is/errors.As)Wrap(cause error) *AppError— attaches internal cause (never serialized to JSON)WithDetails(d any) *AppError— attaches structured details (e.g., validation[]FieldError)apperrors.New(status int, code, message string) *AppError
Named Constructors
| Constructor | HTTP Status | Code |
|---|---|---|
ErrBadRequest(msg) | 400 | BAD_REQUEST |
ErrUnauthorized(msg) | 401 | UNAUTHORIZED |
ErrForbidden(msg) | 403 | FORBIDDEN |
ErrNotFound(msg) | 404 | NOT_FOUND |
ErrConflict(msg) | 409 | CONFLICT |
ErrUnprocessable(msg) | 422 | UNPROCESSABLE_ENTITY |
ErrTooManyRequests(msg) | 429 | TOO_MANY_REQUESTS |
ErrInternalServer(msg) | 500 | INTERNAL_SERVER_ERROR |
ErrNotImplemented(msg) | 501 | NOT_IMPLEMENTED |
ErrServiceUnavailable(msg) | 503 | SERVICE_UNAVAILABLE |
HTTP Response & ErrorHandler() Middleware
In Gin handlers, attach errors via _ = c.Error(err) and return. middleware.ErrorHandler() handles serialization and logging:
- If
erris*AppError: logsErrorlevel whenHTTPStatus >= 500(withcode,method,path,request_id), and writesc.JSON(appErr.HTTPStatus, appErr). - If
erris any othererror: logs the raw error server-side withrequest_id, and writes a sanitized500 INTERNAL_SERVER_ERRORJSON response without leaking internals. apperrors.Respond(c, err)writes the same JSON directly (used by early-abort middlewares such asAppKeyandRateLimiter).
Inspection Helpers
apperrors.Is(err error, code string) boolapperrors.IsNotFound(err),IsBadRequest(err),IsUnauthorized(err),IsForbidden(err),IsConflict(err),IsUnprocessable(err),IsInternalServer(err)apperrors.HTTPStatus(err error) int(defaults to500for non-AppError)
