Skip to Content

Errors

The errors package provides structured error handling with custom error types, HTTP-aware error responses, error wrapping with context, and a standardized set of error codes for consistent API responses.

Import

import "github.com/gofastadev/gofasta/pkg/errors"

Key Types

AppError

The primary error type used throughout Gofasta applications.

type AppError struct { Code string `json:"code"` Message string `json:"message"` Detail string `json:"detail,omitempty"` HTTPStatus int `json:"-"` Err error `json:"-"` } func (e *AppError) Error() string func (e *AppError) Unwrap() error

ErrorResponse

The JSON structure returned to API clients.

type ErrorResponse struct { Error ErrorBody `json:"error"` } type ErrorBody struct { Code string `json:"code"` Message string `json:"message"` Detail string `json:"detail,omitempty"` }

Error Codes

ConstantCodeHTTP StatusDescription
ErrNotFoundNOT_FOUND404Resource not found
ErrBadRequestBAD_REQUEST400Malformed or invalid request
ErrUnauthorizedUNAUTHORIZED401Missing or invalid authentication
ErrForbiddenFORBIDDEN403Insufficient permissions
ErrConflictCONFLICT409Resource conflict (e.g., duplicate)
ErrInternalINTERNAL_ERROR500Unexpected server error
ErrValidationVALIDATION_ERROR422Input validation failure
ErrTimeoutTIMEOUT504Operation timed out
ErrServiceUnavailableSERVICE_UNAVAILABLE503Upstream dependency unavailable

Key Functions

FunctionSignatureDescription
Newfunc New(code string, message string, status int) *AppErrorCreates a new AppError
Wrapfunc Wrap(err error, code string, message string, status int) *AppErrorWraps an existing error with context
NotFoundfunc NotFound(resource string, id string) *AppErrorReturns a 404 error for a missing resource
BadRequestfunc BadRequest(message string) *AppErrorReturns a 400 error
Unauthorizedfunc Unauthorized(message string) *AppErrorReturns a 401 error
Forbiddenfunc Forbidden(message string) *AppErrorReturns a 403 error
Internalfunc Internal(err error) *AppErrorWraps an internal error with a 500 response
Validationfunc Validation(detail string) *AppErrorReturns a 422 validation error
Isfunc Is(err error, code string) boolChecks if an error matches a specific error code
ToResponsefunc ToResponse(err error) (int, ErrorResponse)Converts an error to an HTTP status and JSON response

Usage

Creating Errors

// Simple error creation err := errors.New("PAYMENT_FAILED", "payment processing failed", 402) // Convenience constructors err := errors.NotFound("User", "user-123") // -> {"code":"NOT_FOUND","message":"User not found","detail":"id: user-123"} err := errors.BadRequest("email field is required") err := errors.Unauthorized("token has expired") err := errors.Forbidden("admin role required")

Wrapping Errors

user, err := repo.FindByID(ctx, id) if err != nil { return errors.Wrap(err, "NOT_FOUND", "user not found", 404) } // The original error is preserved and accessible var appErr *errors.AppError if stderrors.As(err, &appErr) { fmt.Println(appErr.Unwrap()) // original error }

Converting to HTTP Responses

func (c *UserController) GetUser(w http.ResponseWriter, r *http.Request) { user, err := c.service.FindUser(ctx, id) if err != nil { status, response := errors.ToResponse(err) httputil.JSON(w, status, response) return } httputil.JSON(w, http.StatusOK, user) }

Checking Error Codes

err := service.CreateUser(ctx, input) if errors.Is(err, "CONFLICT") { // handle duplicate user } if errors.Is(err, "VALIDATION_ERROR") { // handle validation failure }
  • HTTP Utilities — JSON response helpers that work with AppError
  • Validators — Validation errors integrate with this package
  • Middleware — Recovery middleware catches panics and returns error responses
Last updated on