Documentation
¶
Overview ¶
@index HTTP adapters that translate trace errors into API responses, middleware behavior, and client-side classifications.
Package tracehttp holds every part of trace that depends on net/http. It is a separate package so that programs which only need error values, stack frames, and slog integration never pull net/http, encoding/json, or the crypto/tls tree into their binaries.
Index ¶
- Constants
- func ErrorMiddleware(h ErrorHandlerFunc) http.HandlerFunc
- func FromHTTPResponse(resp *http.Response, body []byte) error
- func GetHTTPStatusCode(err error) int
- func IsHTTPError(err error, statusCode int) bool
- func ReadErrorResponse(statusCode int, responseBody []byte) error
- func WrapHTTPError(err error, statusCode int, msg ...string) error
- func WriteError(w http.ResponseWriter, err error, requestID string) error
- type Client
- type ErrorBody
- type ErrorCode
- type ErrorHandlerFunc
- type ErrorResponse
- type HTTPError
- type HTTPErrorProvider
Constants ¶
const StatusClientClosedRequest = 499
StatusClientClosedRequest is the non-standard status used for a request the client canceled before the server finished. It matches nginx's 499.
Variables ¶
This section is empty.
Functions ¶
func ErrorMiddleware ¶
func ErrorMiddleware(h ErrorHandlerFunc) http.HandlerFunc
@intent adapt error-returning handlers into standard net/http handlers. @sideEffect attaches method and path fields before writing the HTTP error response. @ensures renders handler errors through the logger-free safe response writer. ErrorMiddleware converts an ErrorHandlerFunc to a standard http.HandlerFunc.
func FromHTTPResponse ¶
@intent classify an upstream response for developer-facing debugging rather than client rendering. @domainRule 2xx responses are not errors, while known status codes map to typed trace errors. @ensures records the current call site as the first trace frame and stores upstream status metadata in error fields. FromHTTPResponse creates an appropriate error from an HTTP response.
It retains body in the developer-facing error, so the resulting error must not be handed to WriteError on a public boundary. Prefer ReadErrorResponse, which reads the safe JSON envelope and keeps no raw body.
func GetHTTPStatusCode ¶
@intent translate trace error categories into HTTP response codes at service boundaries. @ensures returns HTTP 200 for nil errors and HTTP 500 for unclassifiable errors. GetHTTPStatusCode returns the HTTP status code for an error.
func IsHTTPError ¶
@intent test whether an error chain resolves to a specific HTTP status mapping. @ensures delegates status resolution to GetHTTPStatusCode. IsHTTPError checks if an error corresponds to a specific HTTP status code.
func ReadErrorResponse ¶
@intent restore typed trace semantics from the public ErrorResponse envelope without deserializing internal trace data. @domainRule HTTP 2xx and 3xx statuses are not errors. @domainRule malformed, unknown, or status-mismatched responses fail closed without retaining the raw body. ReadErrorResponse converts a public HTTP error response into a trace error.
func WrapHTTPError ¶
@intent override or attach explicit HTTP status semantics to an existing error chain. @domainRule returns nil unchanged when the source error is nil. @mutates adds http_status metadata to the returned traced wrapper. @ensures the returned error accumulates the caller frame on top of the source frames and carries the source fields forward, so GetFrames and GetFields stay useful after wrapping. WrapHTTPError wraps an error with HTTP status code information.
func WriteError ¶
func WriteError(w http.ResponseWriter, err error, requestID string) error
@intent expose a simple entry point for converting domain errors into HTTP responses. @sideEffect writes status code, headers, and a JSON body to the response writer. @ensures returns without writing anything when the input error is nil. WriteError writes a safe error response without logging.
Types ¶
type Client ¶
@intent wrap http.Client so transport failures come back as trace-classified errors. Client is an HTTP client that wraps errors with trace information.
func NewClient ¶
@intent provide an HTTP client wrapper that returns trace-classified transport failures. @ensures falls back to http.DefaultClient when no custom client is supplied. NewClient creates a new trace-aware HTTP client.
func (*Client) Do ¶
@intent classify outbound HTTP transport failures into timeout or connection problem errors. @domainRule deadline exceeded maps to Timeout and other transport failures map to ConnectionProblem. @sideEffect executes the underlying HTTP request through the wrapped client. Do executes the request and wraps any errors with trace information.
type ErrorBody ¶
type ErrorBody struct {
Code ErrorCode `json:"code"`
Message string `json:"message"`
RequestID string `json:"request_id,omitempty"`
}
@intent group safe client fields under one stable JSON error envelope. ErrorBody is the stable machine-readable body nested under the error key.
type ErrorCode ¶
type ErrorCode string
@intent give clients a stable machine-readable classification independent of HTTP status text. ErrorCode is a stable machine-readable HTTP error classification.
const ( // CodeBadRequest identifies invalid client input. CodeBadRequest ErrorCode = "bad_request" // CodeUnauthenticated identifies a missing or invalid authentication identity. CodeUnauthenticated ErrorCode = "unauthenticated" // CodeAccessDenied identifies an authenticated caller without permission. CodeAccessDenied ErrorCode = "access_denied" // CodeNotFound identifies a missing resource. CodeNotFound ErrorCode = "not_found" // CodeAlreadyExists identifies a duplicate resource. CodeAlreadyExists ErrorCode = "already_exists" // CodeConflict identifies a state conflict. CodeConflict ErrorCode = "conflict" // CodeLimitExceeded identifies a rate or quota limit. CodeLimitExceeded ErrorCode = "limit_exceeded" // CodeCanceled identifies a canceled request. CodeCanceled ErrorCode = "canceled" // CodeNotImplemented identifies unavailable functionality. CodeNotImplemented ErrorCode = "not_implemented" CodeUnavailable ErrorCode = "unavailable" // CodeTimeout identifies a timed-out operation. CodeTimeout ErrorCode = "timeout" // CodeInternal identifies a failure that is intentionally hidden from clients. CodeInternal ErrorCode = "internal" )
type ErrorHandlerFunc ¶
type ErrorHandlerFunc func(w http.ResponseWriter, r *http.Request) error
@intent let HTTP handlers return errors directly so middleware can centralize response rendering. ErrorHandlerFunc is a function that handles HTTP requests and may return an error.
type ErrorResponse ¶
type ErrorResponse struct {
Error ErrorBody `json:"error"`
}
@intent define the client-facing error payload returned by HTTP helpers in this package. ErrorResponse represents a structured JSON error response.
func ErrorResponseFor ¶
func ErrorResponseFor(err error, requestID string) (status int, response ErrorResponse)
@intent build a framework-neutral response from the safe HTTP classification. @domainRule request IDs are caller-supplied and trace fields or details are never copied from err. @ensures returns zero values for nil errors. ErrorResponseFor returns the status and safe response body for err.
type HTTPError ¶
@intent carry only validated status, semantic code, and client-safe message across an HTTP boundary. HTTPError is the safe client-facing representation of an error.
func ToHTTPError ¶
@intent classify an error chain into a validated client-safe HTTP representation. @domainRule the outermost classifiable link in the chain decides the response, so an outer AccessDenied wrap is never overridden by an inner NotFound. @domainRule invalid classifications become internal errors and every 5xx message is sanitized. @ensures returns the zero value for nil and never derives a message from an outer trace wrapper. ToHTTPError returns the safe HTTP representation for err.
type HTTPErrorProvider ¶
@intent let application-owned error types opt into explicit safe HTTP classification. HTTPErrorProvider lets custom errors define a safe HTTP representation.
It is the single extension point for application-defined mapping. An error that implements it wins over this package's built-in classification, and the outermost implementer in a chain wins over inner ones.