errors

package module
v0.22.9 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Sep 12, 2026 License: Apache-2.0 Imports: 7 Imported by: 21,477

README

errors

Tests Coverage CI vuln scan CodeQL

Release CodeFactor Grade License

GoDoc Discord Channel go version Top language Commits since latest release


Shared errors and error interface used throughout the various libraries found in the go-openapi toolkit.

Announcements

  • 2025-12-19 : new community chat on discord
    • a new discord community channel is available to be notified of changes and support users

You may join the discord community by clicking the invite link on the discord badge (also above). Discord Channel

Status

API is stable.

Import this library in your project

go get github.com/go-openapi/errors

Basic usage

const url = "https://www.example.com/#"

errGeneric := New(401,"onvalid argument: %s", url)

errNotFound := NotFound("resource not found: %s", url)

errNotImplemented := NotImplemented("method: %s", url)

Change log

See https://github.com/go-openapi/errors/releases

Licensing

This library ships under the SPDX-License-Identifier: Apache-2.0.

Other documentation

Cutting a new release

Maintainers can cut a new release by either:

  • running this workflow
  • or pushing a semver tag
    • signed tags are preferred
    • The tag message is prepended to release notes

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

Examples

Constants

View Source
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

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

type Error interface {
	error
	Code() int32
}

Error represents a error interface all swagger framework errors implement.

func MethodNotAllowed

func MethodNotAllowed(requested string, allow []string) Error

MethodNotAllowed creates a new method not allowed error.

func New

func New(code int32, message string, args ...any) Error

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 NotFound

func NotFound(message string, args ...any) Error

NotFound creates a new not found error.

func NotImplemented

func NotImplemented(message string) Error

NotImplemented creates a new not implemented error.

func