errors

package
v0.0.1 Latest Latest
Warning

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

Go to latest
Published: Dec 2, 2026 License: Apache-2.0 Imports: 7 Imported by: 1 module, 0 packages

The first number is the count of modules that contain a package that imports this one. The module count is a better indicator of popularity than the package count. A module with 100 importing packages is counted only once instead of 100 times, reflecting the fact that the choice to use the package was likely made only once, not 100 times.
A '?' means that the value hasn't been computed yet.

Documentation

Overview

Package errors reports what went wrong reading or writing a YAML document, with the position it happened at and the lines of source around it.

Every failure raised by the scanner, the parser and the codec is an Error, except the few the codec returns without a position, listed apart below. Match one against the kind it carries:

import (
	"errors"

	yamlerrors "github.com/go-openapi/go-yaml/errors"
)

if errors.Is(err, yamlerrors.ErrDuplicateKey) {
	// ...
}

To reach the position, unwrap to the Error itself:

var yerr *yamlerrors.Error
if errors.As(err, &yerr) {
	fmt.Println(yerr.GetToken().Position)
}

Error prints the message with the source drawn under it. Use FormatError to choose color and whether to draw the source, and FormatErrorAtToken to draw a message of your own at a token.

Index

Constants

This section is empty.

Variables

View Source
var (
	// ErrSyntax reports a document the scanner or the parser could not read.
	ErrSyntax = stderrors.New("syntax error")
	// ErrTypeMismatch reports a value that does not fit the Go type it was
	// decoded into.
	ErrTypeMismatch = stderrors.New("type mismatch")
	// ErrOverflow reports a number too large for the Go type it was decoded
	// into.
	ErrOverflow = stderrors.New("overflow")
	// ErrDuplicateKey reports a mapping with the same key twice, found with
	// the strict duplicate-key check on.
	ErrDuplicateKey = stderrors.New("duplicate key")
	// ErrUnknownField reports a mapping key with no matching struct field,
	// found with the strict unknown-field check on.
	ErrUnknownField = stderrors.New("unknown field")
	// ErrUnexpectedNodeType reports a node of the wrong shape, such as a
	// sequence where a mapping is required.
	ErrUnexpectedNodeType = stderrors.New("unexpected node type")
	// ErrUnhashableKey reports a mapping key Go cannot use as a map key -- a
	// sequence or a mapping, decoded into a map whose key type admits one,
	// such as a map[any]any. A map key must be comparable, and setting one
	// that is not panicked with "hash of unhashable type" until it was
	// reported here. A Go slice, map or function handed to a
	// [github.com/go-openapi/go-yaml/codec.MapSlice] as a key is refused with
	// it too, without a position.
	ErrUnhashableKey = stderrors.New("unhashable map key")
	// ErrNotJSON reports a well-formed YAML document that JSON has no spelling
	// for, found with
	// [github.com/go-openapi/go-yaml/parser.WithJSONCompatible] on. It is not a
	// syntax error: the document is valid YAML and only the conversion is
	// impossible.
	ErrNotJSON = stderrors.New("not convertible to JSON")
	// ErrNotJSONSyntax reports a document not written as JSON, found with
	// [github.com/go-openapi/go-yaml/parser.WithJSONSyntax] on. The document
	// may be valid YAML: "a: b" is, and is not JSON. Under that option every
	// syntax error carries this kind, not [ErrSyntax].
	ErrNotJSONSyntax = stderrors.New("not JSON")
	// ErrUnknownAnchor reports an alias naming an anchor the document does not
	// declare before it. An anchor belongs to the document it was written in
	// and an alias names the most recent one of that name, so an anchor
	// declared later, or in another document, is not one this alias can name.
	ErrUnknownAnchor = stderrors.New("unknown anchor")
	// ErrRecursiveAlias reports an alias standing inside the node its own
	// anchor names, directly or through another anchor. The parser accepts
	// the document and its tree holds the cycle, but a Go value is built by
	// walking and has nowhere to put one.
	ErrRecursiveAlias = stderrors.New("recursive alias")
	// ErrExcessiveAliasing reports a document whose aliases build far more than
	// the document could hold written out. An alias names a node and the value
	// it stands for is built again wherever the alias appears, so a chain of
	// them multiplies: 259 bytes of YAML can name 100,000 values and 423 bytes
	// 387 million.
	ErrExcessiveAliasing = stderrors.New("excessive aliasing")
	// ErrExceededMaxDepth reports a document holding more collections, anchors,
	// tags and "?" keys inside one another than the parser reads: 10,000.
	ErrExceededMaxDepth = stderrors.New("exceeded max depth")
	// ErrValidation reports a struct that the validator passed to
	// [github.com/go-openapi/go-yaml/codec.Validator] returned an error for.
	// The validator's own error stays reachable with [errors.Is] and [errors.As].
	ErrValidation = stderrors.New("validation failed")
	// ErrUnmarshaler reports an error returned by a type that decodes itself: an UnmarshalYAML method,
	// UnmarshalText, UnmarshalJSON under UseJSONUnmarshaler, or a function passed to
	// [github.com/go-openapi/go-yaml/codec.RegisterCustomUnmarshaler].
	// The error carries the position of the node the type was decoding,
	// and the type's own error stays reachable with [errors.Is] and [errors.As].
	ErrUnmarshaler = stderrors.New("unmarshaler failed")
)

The kinds of failure an Error carries. Match one with errors.Is.

View Source
var (
	// ErrDecodeRequiredPointerType reports a decode into a value the decoder
	// cannot write through.
	ErrDecodeRequiredPointerType = stderrors.New("decode target is not a pointer")
	// ErrNotAJSONObject reports JSON that is not an object handed to a type
	// that holds one, such as a
	// [github.com/go-openapi/go-yaml/codec.MapSlice].
	ErrNotAJSONObject = stderrors.New("not a JSON object")
	// ErrUnknownCommentPositionType reports a comment whose position is none
	// of head, line or foot.
	ErrUnknownCommentPositionType = stderrors.New("unknown comment position type")
	// ErrInvalidCommentMapValue reports a nil comment map handed to
	// [github.com/go-openapi/go-yaml/codec.CommentToMap], which has nowhere to
	// put what it collects.
	ErrInvalidCommentMapValue = stderrors.New("nil comment map")
)

The errors the codec returns as they are, with no position. Most report a call the codec cannot serve, whatever the document.

Functions

func FormatError

func FormatError(err error, colored, inclSource bool) string

FormatError renders err, drawing the source around it where err carries one and inclSource asks for it. An error this package did not raise prints as its own Error method returns it.

func FormatErrorAtToken

func FormatErrorAtToken(msg string, tk *token.Token, source []byte, colored, inclSource bool) string

FormatErrorAtToken renders msg as a failure reported at tk, drawing the lines of source around it.

source is the document tk was read from. Drawing a document requires being given one: an Error renders its own context from the text it was found in, and this helper needs the same. Pass nil to print the position and the message alone.

func WithSource

func WithSource(err error, src Source) error

WithSource tells err, and every error wrapped inside it, the text it was found in. An error that never learns keeps its position and prints no document around it.

Types

type Error

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

Error is a failure raised while reading or writing a YAML document.

The kind it carries says what went wrong; errors.Is matches against ErrSyntax and its siblings. GetToken gives the position, and Error draws the lines of source around it once the document has been recorded with WithSource.

func NewDuplicateKey

func NewDuplicateKey(msg string, tk *token.Token) *Error

NewDuplicateKey reports msg as a repeated mapping key at tk.

func NewDuplicateKeyOf

func NewDuplicateKeyOf(d ast.DuplicateKey, tk *token.Token) *Error

NewDuplicateKeyOf reports the repeat d the parse recorded, at tk: ErrNotJSON for two keys that write one JSON member, which a parse under github.com/go-openapi/go-yaml/parser.WithJSONCompatible records, and ErrDuplicateKey for a repeated key or two keys that name one entry. Readers return it for the repeat ast.FirstRefused picks.

func NewExceededMaxDepth

func NewExceededMaxDepth(limit int, tk *token.Token) *Error

NewExceededMaxDepth reports a document nested past limit levels, at tk, the token of the node that opens one level too many.

func NewExcessiveAliasing

func NewExcessiveAliasing(built, budget int, tk *token.Token) *Error

NewExcessiveAliasing reports a decode building more than the document can account for, at tk.

func NewNotJSON

func NewNotJSON(msg string, tk *token.Token) *Error

NewNotJSON reports msg as a document JSON cannot hold, at tk.

func NewNotJSONSyntax

func NewNotJSONSyntax(msg string, tk *token.Token) *Error

NewNotJSONSyntax reports msg as a document not written as JSON, at tk.

func NewOverflow

func NewOverflow(dst reflect.Type, num string, tk *token.Token) *Error

NewOverflow reports the number num as too large for the Go type dst, at tk.

func NewRecursiveAlias

func NewRecursiveAlias(name string, tk *token.Token) *Error

NewRecursiveAlias reports the alias name as standing inside the node its own anchor names, at tk.

The alias is resolved: the message names a cycle, not a missing anchor. See NewUnknownAnchor for that.

func NewSyntax

func NewSyntax(msg string, tk *token.Token) *Error

NewSyntax reports msg as a malformed document at tk.

func NewTypeMismatch

func NewTypeMismatch(dst, src reflect.Type, tk *token.Token) *Error

NewTypeMismatch reports a value of type src decoded into a Go value of type dst, at tk.

func NewUnexpectedNodeType

func NewUnexpectedNodeType(actual, expected ast.NodeType, tk *token.Token) *Error

NewUnexpectedNodeType reports a node of type actual where expected was required, at tk.

func NewUnhashableKey

func NewUnhashableKey(src reflect.Type, tk *token.Token) *Error

NewUnhashableKey reports src as a mapping key Go cannot compare, at tk.

func NewUnknownAnchor

func NewUnknownAnchor(name string, tk *token.Token) *Error

NewUnknownAnchor reports the alias name as naming no anchor, at tk.

func NewUnknownField

func NewUnknownField(msg string, tk *token.Token) *Error

NewUnknownField reports msg as a mapping key with no struct field at tk.

func NewUnmarshaler

func NewUnmarshaler(err error, tk *token.Token) *Error

NewUnmarshaler reports err, returned by a type that decodes itself, at tk.

func NewUnnamedKey

func NewUnnamedKey(kind string, tk *token.Token) *Error

NewUnnamedKey reports a non-scalar key, at tk.

A Go map keyed by a string needs a key with a spelling, and a collection has none: github.com/go-openapi/go-yaml/token.KeyName writes the canonical text of every scalar type and nothing for a sequence or a mapping. A Go map keyed by any refuses one for a second reason -- Go hashes no slice or map.

Go's own printing stood in before, naming the key after the value the decoder built rather than after the document.

func NewValidation

func NewValidation(err error, tk *token.Token) *Error

NewValidation reports err, a validator's error, at tk. The message is err's, and errors.As reaches err through the Error.

func (*Error) As

func (e *Error) As(target any) bool

As lets errors.As reach the error a validation or an unmarshaler error wraps, such as github.com/go-playground/validator/v10's ValidationErrors.

func (*Error) Error

func (e *Error) Error() string

Error returns the message with its position, and the lines of source around it where the document has been recorded with WithSource.

func (*Error) FormatError

func (e *Error) FormatError(colored, inclSource bool) string

FormatError renders the failure, coloring it when colored is set and drawing the source under it when inclSource is set and the document is known.

func (*Error) GetMessage

func (e *Error) GetMessage() string

GetMessage returns the message without the position or the source.

func (*Error) GetToken

func (e *Error) GetToken() *token.Token

GetToken returns the token the failure was found at, nil if the failure carries no position.

func (*Error) Is

func (e *Error) Is(target error) bool

Is lets errors.Is match the error a validation or an unmarshaler error wraps, as well as its kind. Error.Unwrap returns the kind, so this is the way to the validator's own error.

func (*Error) SetStructField

func (e *Error) SetStructField(name string)

SetStructField records name as the struct field a type mismatch was found decoding, replacing any path already there. The decoder builds the path as it unwinds, so a mismatch nested two structs deep reads "Outer.Inner.leaf".

func (*Error) StructField

func (e *Error) StructField() string

StructField returns the struct field path recorded by Error.SetStructField, empty when none was.

func (*Error) Unwrap

func (e *Error) Unwrap() error

Unwrap returns the kind of failure, so that errors.Is matches an Error against ErrSyntax and its siblings.

type Source

type Source struct {
	Text      string
	FirstLine int
}

Source is the text an error was found in, and the number of its first line.

A parse holds the whole document, so the text costs nothing to keep: a Go string shares the bytes it is taken from. A scanner fed from a reader would keep a window around the failure instead, and FirstLine says which line that window starts at.

Jump to

Keyboard shortcuts

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