HTTP Exceptions

GoNest provides a comprehensive set of built-in HTTP exception types for signaling errors in the request pipeline. When thrown, exceptions are caught by exception filters and converted to JSON error responses.

Using Exceptions

Throw exceptions from handlers, guards, pipes, or interceptors by returning them as errors:

func (c *Controller) findOne(ctx gonest.Context) error {
    cat := c.service.FindOne(id)
    if cat == nil {
        return gonest.NewNotFoundException("cat not found")
    }
    return ctx.JSON(http.StatusOK, cat)
}

Default Error Response

The built-in DefaultExceptionFilter produces JSON responses in this format:

{
  "statusCode": 404,
  "message": "cat not found",
  "timestamp": "2025-01-15T10:30:00Z",
  "path": "/cats/99"
}

Built-in Exceptions

ConstructorStatusDescription
NewBadRequestException(msg)400Malformed request
NewUnauthorizedException(msg)401Missing or invalid credentials
NewForbiddenException(msg)403Insufficient permissions
NewNotFoundException(msg)404Resource not found
NewMethodNotAllowedException(msg)405HTTP method not supported
NewNotAcceptableException(msg)406Content negotiation failed
NewRequestTimeoutException(msg)408Request timed out
NewConflictException(msg)409Resource conflict
NewGoneException(msg)410Resource permanently removed
NewPreconditionFailedException(msg)412Precondition not met
NewPayloadTooLargeException(msg)413Request body too large
NewUnsupportedMediaTypeException(msg)415Content type not supported
NewImATeapotException(msg)418I’m a teapot
NewMisdirectedException(msg)421Misdirected request
NewUnprocessableEntityException(msg)422Validation failed
NewTooManyRequestsException(msg)429Rate limit exceeded
NewInternalServerError(msg)500Unexpected server error
NewNotImplementedException(msg)501Not implemented
NewBadGatewayException(msg)502Bad gateway
NewServiceUnavailableException(msg)503Service unavailable
NewGatewayTimeoutException(msg)504Gateway timeout
NewHttpVersionNotSupportedException(msg)505HTTP version not supported

Custom Exceptions

Create exceptions with any status code:

gonest.NewHTTPException(http.StatusTeapot, "I'm a teapot")

Wrapping Errors

Wrap an underlying error for debugging while returning a clean HTTP response:

result, err := db.Query(sql)
if err != nil {
    return gonest.WrapHTTPException(
        http.StatusInternalServerError,
        "database query failed",
        err,
    )
}

The wrapped error is accessible via Unwrap() for logging or inspection in custom exception filters.

HTTPException API

type HTTPException struct {
    StatusCode int
    Message    string
    Cause      error // optional wrapped error
}

// Implements the error interface
func (e *HTTPException) Error() string
func (e *HTTPException) Unwrap() error

Exception Filters

See Exception Filters for how to customize error handling with global, controller-level, and route-level filters.