Documentation
¶
Overview ¶
Package errors provides an Error interface and several concrete types implementing this interface to manage API errors and JSON-schema validation errors.
A middleware handler ServeError() is provided to serve the errors types it defines.
It is used throughout the various go-openapi toolkit libraries. (https://github.com/go-openapi).
Index ¶
- Constants
- Variables
- func ServeError(rw http.ResponseWriter, r *http.Request, err error)
- type APIVerificationFailed
- type CompositeError
- type Error
- type MethodNotAllowedError
- type ParseError
- type Validation
- func AdditionalItemsNotAllowed(name, in string) *Validation
- func DuplicateItems(name, in string) *Validation
- func EnumFail(name, in string, value any, values []any) *Validation
- func ExceedsMaximum(name, in string, maximum float64, exclusive bool, value any) *Validation
- func ExceedsMaximumInt(name, in string, maximum int64, exclusive bool, value any) *Validation
- func ExceedsMaximumUint(name, in string, maximum uint64, exclusive bool, value any) *Validation
- func ExceedsMinimum(name, in string, minimum float64, exclusive bool, value any) *Validation
- func ExceedsMinimumInt(name, in string, minimum int64, exclusive bool, value any) *Validation
- func ExceedsMinimumUint(name, in string, minimum uint64, exclusive bool, value any) *Validation
- func FailedAllPatternProperties(name, in, key string) *Validation
- func FailedPattern(name, in, pattern string, value any) *Validation
- func InvalidCollectionFormat(name, in, format string) *Validation
- func InvalidContentType(value string, allowed []string) *Validation
- func InvalidResponseFormat(value string, allowed []string) *Validation
- func InvalidType(name, in, typeName string, value any) *Validation
- func InvalidTypeName(typeName string) *Validation
- func MultipleOfMustBePositive(name, in string, factor any) *Validation
- func NotMultipleOf(name, in string, multiple, value any) *Validation
- func PropertyNotAllowed(name, in, key string) *Validation
- func ReadOnly(name, in string, value any) *Validation
- func Required(name, in string, value any) *Validation
- func TooFewItems(name, in string, minimum int64, value any) *Validation
- func TooFewProperties(name, in string, n int64) *Validation
- func TooLong(name, in string, maximum int64, value any) *Validation
- func TooManyItems(name, in string, maximum int64, value any) *Validation
- func TooManyProperties(name, in string, n int64) *Validation
- func TooShort(name, in string, minimum int64, value any) *Validation
Examples ¶
Constants ¶
const ( // CompositeErrorCode remains 422 for backwards-compatibility // and to separate it from validation errors with cause. CompositeErrorCode = http.StatusUnprocessableEntity // InvalidTypeCode is used for any subclass of invalid types. InvalidTypeCode = maximumValidHTTPCode + iota // RequiredFailCode indicates a required field is missing. RequiredFailCode TooLongFailCode TooShortFailCode PatternFailCode EnumFailCode MultipleOfFailCode MaxFailCode MinFailCode UniqueFailCode MaxItemsFailCode MinItemsFailCode NoAdditionalItemsCode TooFewPropertiesCode TooManyPropertiesCode UnallowedPropertyCode FailedAllPatternPropsCode MultipleOfMustBePositiveCode ReadOnlyFailCode )
All code responses can be used to differentiate errors for different handling by the consuming program.
Variables ¶
var DefaultHTTPCode = http.StatusUnprocessableEntity
DefaultHTTPCode is used when the error Code cannot be used as an HTTP code.
Functions ¶
func ServeError ¶
func ServeError(rw http.ResponseWriter, r *http.Request, err error)
ServeError implements the http error handler interface.
Example ¶
package main
import (
"encoding/json"
"fmt"
"net/http"
"net/http/httptest"
"github.com/go-openapi/errors"
)
func main() {
// Create a simple validation error
err := errors.Required("email", "body", nil)
// Simulate HTTP response
recorder := httptest.NewRecorder()
request := httptest.NewRequest(http.MethodPost, "/api/users", nil)
// Serve the error as JSON
errors.ServeError(recorder, request, err)
fmt.Printf("status: %d\n", recorder.Code)
fmt.Printf("content-type: %s\n", recorder.Header().Get("Content-Type"))
// Parse and display the JSON response
var response map[string]any
if err := json.Unmarshal(recorder.Body.Bytes(), &response); err == nil {
fmt.Printf("error code: %.0f\n", response["code"])
fmt.Printf("error message: %s\n", response["message"])
}
}
Output: status: 422 content-type: application/json error code: 602 error message: email in body is required
Types ¶
type APIVerificationFailed ¶
type APIVerificationFailed struct {
Section string `json:"section,omitempty"`
MissingSpecification []string `json:"missingSpecification,omitempty"`
MissingRegistration []string `json:"missingRegistration,omitempty"`
}
APIVerificationFailed is an error that contains all the missing info for a mismatched section between the api registrations and the api spec.
func (*APIVerificationFailed) Error ¶
func (v *APIVerificationFailed) Error() string
Error implements the standard error interface.
type CompositeError ¶
type CompositeError struct {
Errors []error
// contains filtered or unexported fields
}
CompositeError is an error that groups several errors together.
func CompositeValidationError ¶
func CompositeValidationError(errors ...error) *CompositeError
CompositeValidationError an error to wrap a bunch of other errors.
Example ¶
package main
import (
"fmt"
"github.com/go-openapi/errors"
)
func main() {
errs := make([]error, 0, 3)
// Collect multiple validation errors
errs = append(errs, errors.Required("name", "body", nil))
errs = append(errs, errors.TooShort("description", "body", 10, "short"))
errs = append(errs, errors.InvalidType("age", "body", "integer", "abc"))
// Combine them into a composite error
compositeErr := errors.CompositeValidationError(errs...)
fmt.Printf("error count: %d\n", len(errs))
fmt.Printf("composite error: %v\n", compositeErr)
fmt.Printf("code: %d\n", compositeErr.Code())
// Can unwrap to access individual errors
if unwrapped := compositeErr.Unwrap(); unwrapped != nil {
fmt.Printf("unwrapped count: %d\n", len(unwrapped))
}
}
Output: error count: 3 composite error: validation failure list: name in body is required description in body should be at least 10 chars long age in body must be of type integer: "abc" code: 422 unwrapped count: 3
func (*CompositeError) Code ¶
func (c *CompositeError) Code() int32
Code returns the HTTP status code for this composite error.
func (*CompositeError) Error ¶
func (c *CompositeError) Error() string
Error implements the standard error interface.
func (CompositeError) MarshalJSON ¶ added in v0.20.0
func (c CompositeError) MarshalJSON() ([]byte, error)
MarshalJSON implements the JSON encoding interface.
func (*CompositeError) Unwrap ¶ added in v0.21.0
func (c *CompositeError) Unwrap() []error
Unwrap implements the errors.Unwrap interface.
func (*CompositeError) ValidateName ¶ added in v0.20.1
func (c *CompositeError) ValidateName(name string) *CompositeError
ValidateName recursively sets the name for all validations or updates them for nested properties.
type Error ¶
Error represents a error interface all swagger framework errors implement.
func MethodNotAllowed ¶
MethodNotAllowed creates a new method not allowed error.
func New ¶
New creates a new API error with a code and a message.
Example ¶
package main
import (
"fmt"
"github.com/go-openapi/errors"
)
func main() {
// Create a generic API error with custom code
err := errors.New(400, "invalid input: %s", "email")
fmt.Printf("error: %v\n", err)
fmt.Printf("code: %d\n", err.Code())
// Create common HTTP errors
notFound := errors.NotFound("user %s not found", "john-doe")
fmt.Printf("not found: %v\n", notFound)
fmt.Printf("not found code: %d\n", notFound.Code())
notImpl := errors.NotImplemented("feature: dark mode")
fmt.Printf("not implemented: %v\n", notImpl)
}
Output: error: invalid input: email code: 400 not found: user john-doe not found not found code: 404 not implemented: feature: dark mode
func NotImplemented ¶
NotImplemented creates a new not implemented error.