Skip to content

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 with errors.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 ​

ConstructorHTTP StatusCode
ErrBadRequest(msg)400BAD_REQUEST
ErrUnauthorized(msg)401UNAUTHORIZED
ErrForbidden(msg)403FORBIDDEN
ErrNotFound(msg)404NOT_FOUND
ErrConflict(msg)409CONFLICT
ErrUnprocessable(msg)422UNPROCESSABLE_ENTITY
ErrTooManyRequests(msg)429TOO_MANY_REQUESTS
ErrInternalServer(msg)500INTERNAL_SERVER_ERROR
ErrNotImplemented(msg)501NOT_IMPLEMENTED
ErrServiceUnavailable(msg)503SERVICE_UNAVAILABLE

HTTP Response & ErrorHandler() Middleware ​

In Gin handlers, attach errors via _ = c.Error(err) and return. middleware.ErrorHandler() handles serialization and logging:

  • If err is *AppError: logs Error level when HTTPStatus >= 500 (with code, method, path, request_id), and writes c.JSON(appErr.HTTPStatus, appErr).
  • If err is any other error: logs the raw error server-side with request_id, and writes a sanitized 500 INTERNAL_SERVER_ERROR JSON response without leaking internals.
  • apperrors.Respond(c, err) writes the same JSON directly (used by early-abort middlewares such as AppKey and RateLimiter).

Inspection Helpers ​

  • apperrors.Is(err error, code string) bool
  • apperrors.IsNotFound(err), IsBadRequest(err), IsUnauthorized(err), IsForbidden(err), IsConflict(err), IsUnprocessable(err), IsInternalServer(err)
  • apperrors.HTTPStatus(err error) int (defaults to 500 for non-AppError)

Released under the Apache-2.0 License.