problems

package module
v0.2.0-beta.10 Latest Latest
Warning

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

Go to latest
Published: May 22, 2025 License: MIT Imports: 13 Imported by: 1

README

problems

Problem Details for HTTP APIs RFC7807

golang library for handling HTTP API errors defined in RFC9457(HTTP JSON Problem Details)

RFC9457(HTTP JSON Problem Details)で定義されたHTTP APIのエラーを扱うためのGO言語のライブラリーです。

Can handle http api error details as golang error

http apiのエラー詳細をgolangのerrorとして処理できます。

Simple Usage

problem := problems.New(problems.Instance("/users")).NotFound("user not found")

Bad Request (RFC7807)

if err := validate.Struct(s); err != nil {
    problems.New(problems.Path(req), problems.InvalidParams(err)).BadRequest("Invalid Parameters").JSON(ctx, req.Writer)
	return
}

Bad Request (RFC9457)

if err := validate.Struct(s); err != nil {
    problems.New(problems.Path(req), problems.ValidationErrors(err)).BadRequest("Invalid Parameters").JSON(ctx, req.Writer)
	return
}

Conversion to error

err := problems.New().Unauthorized("password mismatch").Wrap()
problems.Of(context.TODO, "/login", err).JSON(ctx, req.Writer)

Documentation

Index

Constants

View Source
const (
	Ns9457 = "urn:ietf:rfc:9457"
	Ns7807 = "urn:ietf:rfc:7807"
)
View Source
const (
	DefaultType = "about:blank"
)

Variables

This section is empty.

Functions

func EncodeMap

func EncodeMap(e *xml.Encoder, ex map[string]interface{}) error

func NewBadRequest

func NewBadRequest(err error, params ...InvalidParam) func(p *ProblemDetails) Problem

NewBadRequest Deprecated: use ValidationErrors instead

func NewCodeProblem

func NewCodeProblem(code string, typ ...string) func(p *ProblemDetails) Problem

NewCodeProblem Deprecated: use Code instead

func RegisterXmlMarshaller

func RegisterXmlMarshaller(name string, fn XmlMarshaler) error

func RegisterXmlUnmarshaler

func RegisterXmlUnmarshaler(name string, fn XmlUnmarshaler) error

func WriteJson

func WriteJson(ctx context.Context, w http.ResponseWriter, status int, v interface{})

func WriteXml

func WriteXml(ctx context.Context, w http.ResponseWriter, status int, v interface{})

Types

type Arg

type Arg func(*option)

func WithFromError

func WithFromError(f FromError) Arg

type BadRequest

type BadRequest interface {
	SetValidationErrors(ve []ValidationError)
	SetInvalidParams(params []InvalidParam)
}

type Builder

type Builder struct {
	// contains filtered or unexported fields
}

func New

func New(opt ...Option) *Builder

func (*Builder) BadGateway

func (b *Builder) BadGateway(format string, args ...interface{}) Problem

func (*Builder) BadRequest

func (b *Builder) BadRequest(format string, args ...interface{}) Problem

func (*Builder) Build

func (b *Builder) Build(status int, format string, args ...interface{}) Problem

func (*Builder) Conflict

func (b *Builder) Conflict(format string, args ...interface{}) Problem

func (*Builder) ExpectationFailed

func (b *Builder) ExpectationFailed(format string, args ...interface{}) Problem

func (*Builder) FailedDependency

func (b *Builder) FailedDependency(format string, args ...interface{}) Problem

func (*Builder) Forbidden

func (b *Builder) Forbidden(format string, args ...interface{}) Problem

func (*Builder) GatewayTimeout

func (b *Builder) GatewayTimeout(format string, args ...interface{}) Problem

func (*Builder) Gone

func (b *Builder) Gone(format string, args ...interface{}) Problem

func (*Builder) HTTPVersionNotSupported

func (b *Builder) HTTPVersionNotSupported(format string, args ...interface{}) Problem

func (*Builder) InsufficientStorage

func (b *Builder) InsufficientStorage(format string, args ...interface{}) Problem

func (*Builder) InternalServerError

func (b *Builder) InternalServerError(format string, args ...interface{}) Problem

func (*Builder) LengthRequired

func (b *Builder) LengthRequired(format string, args ...interface{}) Problem

func (*Builder) Locked

func (b *Builder) Locked(format string, args ...interface{}) Problem

func (*Builder) LoopDetected

func (b *Builder) LoopDetected(format string, args ...interface{}) Problem

func (*Builder) MethodNotAllowed

func (b *Builder) MethodNotAllowed(format string, args ...interface{}) Problem

func (*Builder) MisdirectedRequest

func (b *Builder) MisdirectedRequest(format string, args ...interface{}) Problem

func (*Builder) NetworkAuthenticationRequired

func (b *Builder) NetworkAuthenticationRequired(format string, args ...interface{}) Problem

func (*Builder) NotAcceptable

func (b *Builder) NotAcceptable(format string, args ...interface{}) Problem

func (*Builder) NotExtended

func (b *Builder) NotExtended(format string, args ...interface{}) Problem

func (*Builder) NotFound

func (b *Builder) NotFound(format string, args ...interface{}) Problem

func (*Builder) NotImplemented

func (b *Builder) NotImplemented(format string, args ...interface{}) Problem

func (*Builder) PaymentRequired

func (b *Builder) PaymentRequired(format string, args ...interface{}) Problem

func (*Builder) PreconditionFailed

func (b *Builder) PreconditionFailed(format string, args ...interface{}) Problem

func (*Builder) PreconditionRequired

func (b *Builder) PreconditionRequired(format string, args ...interface{}) Problem

func (*Builder) ProxyAuthRequired

func (b *Builder) ProxyAuthRequired(format string, args ...interface{}) Problem

func (*Builder) RequestEntityTooLarge

func (b *Builder) RequestEntityTooLarge(format string, args ...interface{}) Problem

func (*Builder) RequestHeaderFieldsTooLarge

func (b *Builder) RequestHeaderFieldsTooLarge(format string, args ...interface{}) Problem

func (*Builder) RequestTimeout

func (b *Builder) RequestTimeout(format string, args ...interface{}) Problem

func (*Builder) RequestURITooLong

func (b *Builder) RequestURITooLong(format string, args ...interface{}) Problem

func (*Builder) RequestedRangeNotSatisfiable

func (b *Builder) RequestedRangeNotSatisfiable(format string, args ...interface{}) Problem

func (*Builder) ServiceUnavailable

func (b *Builder) ServiceUnavailable(format string, args ...interface{}) Problem

func (*Builder) Teapot

func (b *Builder) Teapot(format string, args ...interface{}) Problem

func (*Builder) TooEarly

func (b *Builder) TooEarly(format string, args ...interface{}) Problem

func (*Builder) TooManyRequests

func (b *Builder) TooManyRequests(format string, args ...interface{}) Problem

func (*Builder) Type

func (b *Builder) Type(format string, args ...interface{}) *Builder

Type sets the type of the problem

func (*Builder) Unauthorized

func (b *Builder) Unauthorized(format string, args ...interface{}) Problem

func (*Builder) Unavailable

func (b *Builder) Unavailable(format string, args ...interface{}) Problem

Unavailable is an alias for ServiceUnavailable Deprecated: Use ServiceUnavailable instead

func (*Builder) UnavailableForLegalReasons

func (b *Builder) UnavailableForLegalReasons(format string, args ...interface{}) Problem

func (*Builder) UnprocessableEntity

func (b *Builder) UnprocessableEntity(format string, args ...interface{}) Problem

func (*Builder) UnsupportedMediaType

func (b *Builder) UnsupportedMediaType(format string, args ...interface{}) Problem

func (*Builder) UpgradeRequired

func (b *Builder) UpgradeRequired(format string, args ...interface{}) Problem

func (*Builder) VariantAlsoNegotiates

func (b *Builder) VariantAlsoNegotiates(format string, args ...interface{}) Problem

type CodeProblem

type CodeProblem interface {
	SetCode(code string)
}

type DefaultProblem

type DefaultProblem = ProblemDetail

DefaultProblem Deprecated: use ProblemDetail instead

type Extendable

type Extendable interface {
	Extended() bool
	Map() (map[string]interface{}, bool)
}

type FromError

type FromError func(err error) (Problem, bool)

type InvalidParam

type InvalidParam struct {
	XMLName xml.Name `json:"-" xml:"invalid-param"`
	Name    string   `json:"name" xml:"name"`
	Reason  string   `json:"reason" xml:"reason"`
}

func (InvalidParam) MarshalXML

func (ip InvalidParam) MarshalXML(e *xml.Encoder, start xml.StartElement) error

type MsgFunc

type MsgFunc func() string

MsgFunc 詳細メッセージ設定用 Deprecated: use ProblemDetails instead

type Option

type Option func(p Problem) Problem

func Code

func Code(code string) Option

func Detail

func Detail(detail string) Option

func Error

func Error(err error) Option

func Extension

func Extension(key string, value interface{}) Option

func Instance

func Instance(instance string) Option

func InvalidParams

func InvalidParams(err error, params ...InvalidParam) Option

InvalidParams Create RFC7807-style validation error messages

func Path

func Path(req *http.Request) Option

func Status

func Status(status int) Option

func Tag

func Tag(tag string) Option

func Title

func Title(title string) Option

func Type

func Type(format string, args ...interface{}) Option

func ValidationErrors

func ValidationErrors(err error, verrs ...ValidationError) Option

ValidationErrors Create RFC9457-style validation error messages.

type Problem

type Problem interface {
	// ProblemStatus returns the status code of the problem.
	// Deprecated: Use StatusCode instead.
	ProblemStatus() int
	// StatusCode returns the status code of the problem.
	StatusCode() int
	Error() string
	Wrap() error
	String() string
	WithMessage(format string, args ...interface{}) Problem
	Message() string
	Renderer
}

func As

func As(err error, status ...int) (Problem, bool)

As checks if the error is of type Problem and matches the given status codes.

func Bind

func Bind(ctx context.Context, status int, body []byte, f ...func(status int) Problem) (problem Problem, err error)

Bind is a convenience function to bind the request body to a Problem instance. Deprecated: Use UnmarshalJson instead.

func Decode

func Decode(ctx context.Context, status int, body io.Reader, f ...func(status int) Problem) (problem Problem, err error)

Decode is a convenience function to decode the request body into a Problem instance. Deprecated: Use DecodeJson instead.

func DecodeJson

func DecodeJson(ctx context.Context, status int, body io.Reader, f ...func(status int) Problem) (problem Problem, err error)

DecodeJson is a convenience function to decode the io.Reader into a Problem instance.

func DecodeXml

func DecodeXml(ctx context.Context, status int, body io.Reader, f ...func(status int) Problem) (problem Problem, err error)

DecodeXml is a convenience function to decode the io.Reader into a Problem instance.

func Of

func Of(ctx context.Context, path string, err error, args ...Arg) Problem

func ServerProblemOf

func ServerProblemOf(ctx context.Context, path string, err error, f ...MsgFunc) Problem

ServerProblemOf 旧バージョン互換用 Deprecated: use Of instead

func UnmarshalJson

func UnmarshalJson(ctx context.Context, status int, body []byte, f ...func(status int) Problem) (problem Problem, err error)

UnmarshalJson is a convenience function to unmarshal the json body into a Problem instance.

func UnmarshalXml

func UnmarshalXml(ctx context.Context, status int, body []byte, f ...func(status int) Problem) (problem Problem, err error)

UnmarshalXml is a convenience function to unmarshal the xml body into a Problem instance.

type ProblemDetail

type ProblemDetail interface {
	SetDetail(detail string)
}

type ProblemDetails

type ProblemDetails struct {
	XMLName       xml.Name          `json:"-" xml:"problem"`
	Xmlns         string            `json:"-" xml:"xmlns,attr"`
	Type          string            `json:"type" xml:"type"`
	Title         string            `json:"title" xml:"title,attr,omitempty"`
	Status        int               `json:"status,omitempty" xml:"status,attr,omitempty"`
	Detail        string            `json:"detail,omitempty" xml:"xsd:detail,attr,omitempty"`
	Instance      string            `json:"instance,omitempty" xml:"instance,attr,omitempty"`
	Code          string            `json:"code,omitempty" xml:"code,attr,omitempty"`
	InvalidParams []InvalidParam    `json:"invalid-params,omitempty" xml:"invalid-params,omitempty"`
	Errors        []ValidationError `json:"errors,omitempty" xml:"errors,omitempty"`
	// contains filtered or unexported fields
}

func NewDetails

func NewDetails(status int) *ProblemDetails

NewDetails creates a new ProblemDetails instance with the given status code.

func (*ProblemDetails) Error

func (p *ProblemDetails) Error() string

Error returns the JSON representation of the ProblemDetails struct.

func (*ProblemDetails) Extended

func (p *ProblemDetails) Extended() bool

Extended checks if the ProblemDetails struct has any extensions.

func (*ProblemDetails) Extension

func (p *ProblemDetails) Extension(key string, value interface{})

func (*ProblemDetails) JSON

JSON marshals the ProblemDetails struct into JSON format.

func (*ProblemDetails) Map

func (p *ProblemDetails) Map() (map[string]interface{}, bool)

Map returns a map representation of the ProblemDetails struct.

func (*ProblemDetails) MarshalXML

func (p *ProblemDetails) MarshalXML(e *xml.Encoder, start xml.StartElement) error

MarshalXML marshals the ProblemDetails struct into XML format.

func (*ProblemDetails) Message

func (p *ProblemDetails) Message() string

Message returns the detail message of the problem.

func (*ProblemDetails) Problem

func (p *ProblemDetails) Problem() Problem

Problem 旧バージョン互換用 Deprecated: use ProblemDetails instead

func (*ProblemDetails) ProblemStatus

func (p *ProblemDetails) ProblemStatus() int

ProblemStatus returns the status code of the problem. Deprecated: Use StatusCode instead.

func (*ProblemDetails) SetCode

func (p *ProblemDetails) SetCode(code string)

func (*ProblemDetails) SetDetail

func (p *ProblemDetails) SetDetail(detail string)

func (*ProblemDetails) SetInstance

func (p *ProblemDetails) SetInstance(instance string)

func (*ProblemDetails) SetInvalidParams

func (p *ProblemDetails) SetInvalidParams(params []InvalidParam)

func (*ProblemDetails) SetParams

func (p *ProblemDetails) SetParams(url, detail string)

func (*ProblemDetails) SetStatus

func (p *ProblemDetails) SetStatus(status int)

func (*ProblemDetails) SetTitle

func (p *ProblemDetails) SetTitle(title string)

func (*ProblemDetails) SetType

func (p *ProblemDetails) SetType(url string)

func (*ProblemDetails) SetValidationErrors

func (p *ProblemDetails) SetValidationErrors(ve []ValidationError)

func (*ProblemDetails) StatusCode

func (p *ProblemDetails) StatusCode() int

StatusCode returns the status code of the problem.

func (*ProblemDetails) String

func (p *ProblemDetails) String() string

String returns the JSON representation of the ProblemDetails struct.

func (*ProblemDetails) UnmarshalXML

func (p *ProblemDetails) UnmarshalXML(d *xml.Decoder, start xml.StartElement) error

UnmarshalXML unmarshals the XML data into the ProblemDetails struct.

func (*ProblemDetails) Unwrap

func (p *ProblemDetails) Unwrap() error

Unwrap returns the underlying error wrapped by the ProblemDetails struct.

func (*ProblemDetails) WithMessage

func (p *ProblemDetails) WithMessage(format string, args ...interface{}) Problem

WithMessage sets the detail message of the problem.

func (*ProblemDetails) Wrap

func (p *ProblemDetails) Wrap() error

Wrap wraps the ProblemDetails struct with an error.

func (*ProblemDetails) WrapError

func (p *ProblemDetails) WrapError(err error)

func (*ProblemDetails) XML

XML marshals the ProblemDetails struct into XML format.

type ProblemError

type ProblemError = ProblemDetails

ProblemError Deprecated: use ProblemDetails instead

type ProblemExtension

type ProblemExtension interface {
	Extension(key string, value interface{})
}

type ProblemInstance

type ProblemInstance interface {
	SetInstance(instance string)
}

type ProblemStatus

type ProblemStatus interface {
	SetStatus(status int)
}

type ProblemTitle

type ProblemTitle interface {
	SetTitle(title string)
}

type ProblemType

type ProblemType interface {
	SetType(url string)
}

type Renderer

type Renderer interface {
	JSON(ctx context.Context, w http.ResponseWriter)
	XML(ctx context.Context, w http.ResponseWriter)
}

type ValidationError

type ValidationError struct {
	XMLName xml.Name `json:"-" xml:"error"`
	Detail  string   `json:"detail" xml:"detail"`
	Pointer string   `json:"pointer" xml:"pointer"`
}

func (ValidationError) Error

func (ve ValidationError) Error() string

func (ValidationError) MarshalXML

func (ve ValidationError) MarshalXML(e *xml.Encoder, start xml.StartElement) error

type Wrapper

type Wrapper interface {
	WrapError(err error)
	Unwrap() error
}

type XmlMarshaler

type XmlMarshaler func(e *xml.Encoder, start xml.StartElement, v interface{}) error

type XmlUnmarshaler

type XmlUnmarshaler func(d *xml.Decoder, start xml.StartElement) (interface{}, error)

func BoolArray

func BoolArray() XmlUnmarshaler

func Float32Array

func Float32Array() XmlUnmarshaler

func Float64Array

func Float64Array() XmlUnmarshaler

func Int8Array

func Int8Array() XmlUnmarshaler

func Int16Array

func Int16Array() XmlUnmarshaler

func Int32Array

func Int32Array() XmlUnmarshaler

func Int64Array

func Int64Array() XmlUnmarshaler

func IntArray

func IntArray() XmlUnmarshaler

func StringArray

func StringArray() XmlUnmarshaler

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL