errors

package
v1.0.27 Latest Latest
Warning

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

Go to latest
Published: Nov 7, 2026 License: Apache-2.0 Imports: 5 Imported by: 2

Documentation

Overview

Package errors provides types and function used to implement MeshKit compatible errors across the Meshery code base.

Uniform definition of errors using these types and functions facilitates extracting error information directly from the code and generating and publishing error code reference documentation automatically. The error utility tool in this module, /cmd/errorutil, is part of this toolchain.

It depends on a few conventions in order to work:

1) An error code defined as a constant or variable (preferably constant), of type string. The naming convention for these variables is the regex "^Err[A-Z].+Code$", e.g. ErrApplyManifestCode. The initial value of the code is a placeholder string, e.g. "replace_me", set by the developer. The final value of the code is an integer, set by the errorutil tool, as part of a CI workflow.

2) Error details defined using the function New(...), NewV2(...) or NewV3(...) in this package, see below for details. NewV3 nests each probable cause with the remediations that answer it, and each remediation can carry an action and an ActionPolicy; the flat probable cause and remediation lists are derived from it.

Additionally, the following conventions apply:

Errors are defined in each package, in a file named error.go. Errors are namespaced to Meshery components, i.e. they need to be unique within a component. (Often, a specific component corresponds to one git repository.) There are no predefined error code ranges for components. Every component is free to use its own range. Codes carry no meaning, as e.g. HTTP status codes do.

See also the doc command of errorutil, and https://docs.meshery.io/project/contributing/contributing-error.

Example:

 const  ErrConnectCode        = "11000"
 func ErrConnect(err error) error {
	  return errors.New(ErrConnectCode,
	                    errors.Alert,
	                    []string{"Connection to broker failed"},
	                    []string{err.Error()},
	                    []string{"Endpoint might not be reachable"},
	                    []string{"Make sure the NATS endpoint is reachable"})
 }

Index

Constants

View Source
const (
	// Automatic lets a client run the remediation's Action without asking, then tell the person it did.
	Automatic = errorcode.ActionPolicyAutomatic
	// RequiresApproval lets a client run the remediation's Action only after a person approves it.
	RequiresApproval = errorcode.ActionPolicyRequiresApproval
	// Manual means a person applies the remediation; a client shows it and runs nothing.
	// An empty ActionPolicy is Manual.
	Manual = errorcode.ActionPolicyManual
)
View Source
const (
	Emergency = iota // System unusable
	None             // None severity
	Alert            // Immediate action needed
	Critical         // Critical condition—default level
	Fatal            // Fatal condition
)

Variables

View Source
var (
	NoneString = []string{noneText}
)

Functions

func CausesToSchema added in v1.0.25

func CausesToSchema(causes []Cause) []errorcode.ProbableCause

CausesToSchema returns causes as the schemas construct's ProbableCause list, or nil when there are none.

func FlattenCauses added in v1.0.25

func FlattenCauses(causes []Cause) (probableCause, suggestedRemediation []string)

FlattenCauses derives the flat lists earlier consumers read from nested causes: probableCause is each cause's Description in order, and suggestedRemediation is each remediation's Description walking the causes in order, a remediation ID kept the first time it appears. Remediations without an ID are never merged. This is errorcode.FlattenProbableCauses for MeshKit's source types.

func GetCause

func GetCause(err error) string

func GetCode

func GetCode(err error) string

func GetLDescription added in v0.8.54

func GetLDescription(err error) string

func GetRemedy

func GetRemedy(err error) string

func GetSDescription

func GetSDescription(err error) string

func IsID added in v1.0.25

func IsID(s string) bool

IsID reports whether s is a well-formed cause or remediation id: lowercase words joined by hyphens, for example `cluster-unreachable`.

func IsSchemaSeverity added in v1.0.25

func IsSchemaSeverity(s errorcode.ErrorSeverity) bool

IsSchemaSeverity reports whether s is one of the eight levels of the schemas ErrorSeverity ladder.

func JoinDescription added in v1.0.25

func JoinDescription(lines []string) string

JoinDescription joins MeshKit description lines into the single string the schemas construct carries: lines joined with ". ", each line's own trailing period dropped first so no line ends in "..". Empty lines and the "None" placeholder are skipped; the result is empty when nothing remains.

func NonEmptyLines added in v1.0.25

func NonEmptyLines(lines []string) []string

NonEmptyLines returns lines trimmed, without empty lines and MeshKit's "None" placeholder, which the schemas flat lists do not allow.

func ValidateCauses added in v1.0.25

func ValidateCauses(causes []Cause) error

ValidateCauses checks causes against the schemas error construct (docs/error-definition-contract.md in meshery/schemas): ids present and well formed, cause ids unique, a repeated remediation id identical wherever it appears, every cause with at least one remediation, a known ActionPolicy, and an Action behind every Automatic or RequiresApproval policy. errorutil runs the same checks on NewV3 call sites, so a definition that fails here fails the component's error analysis.

Types

type ActionPolicy added in v1.0.25

type ActionPolicy = errorcode.ActionPolicy

ActionPolicy says whether a client may apply a Remediation's Action on its own. It is the schemas error construct's ActionPolicy (meshery/schemas#1334), reused so MeshKit and every consumer share one set of values.

type Cause added in v1.0.25

type Cause struct {
	// ID is stable once published and unique within the error: lowercase words
	// joined by hyphens, for example `service-not-running`. Events name the
	// causes that applied to an occurrence by this ID.
	ID string `json:"id"`
	// Description says what may have caused the error.
	Description string `json:"description"`
	// Remediations answer this cause, the most likely fix first. Never empty.
	Remediations []Remediation `json:"remediations"`
}

Cause is one probable cause of an error with the remediations that answer it, written in source for errors.NewV3. Its JSON form is the schemas construct's ProbableCause (`id`, `description`, `remediations`).

func GetCauses added in v1.0.25

func GetCauses(err error) []Cause

GetCauses returns the nested causes of a MeshKit error created with NewV3, or nil for any other error (including New and NewV2 errors, whose flat lists are unpaired).

func (Cause) ToSchema added in v1.0.25

func (c Cause) ToSchema() errorcode.ProbableCause

ToSchema returns the cause as the schemas construct's ProbableCause.

type Error

type Error struct {
	Code                 string
	Severity             Severity
	ShortDescription     []string
	LongDescription      []string
	ProbableCause        []string
	SuggestedRemediation []string
}

func Is

func Is(err error) (*Error, bool)

func New

func New(code string, severity Severity, sdescription []string, ldescription []string, probablecause []string, remedy []string) *Error

New returns a MeshKit error using the provided parameters.

In order to create MeshKit compatible errors that can be handled by the errorutil tool, consider the following points:

The first parameter, 'code', has to be passed as the error code constant (or variable), not a string literal.

The second parameter, 'severity', has its own type; consult its Go-doc for further details.

The remaining parameters are string arrays for short and long description, probable cause, and suggested remediation. Use string literals in these string arrays, not constants or variables, for any static texts or format strings. Capitalize the first letter of each statement. Call expressions can be used but will be ignored by the tool when exporting error details for the documentation. Do not concatenate strings using the '+' operator, just add multiple elements to the string array.

Example:

errors.New(ErrConnectCode,
           errors.Alert,
           []string{"Connection to broker failed"},
           []string{err.Error()},
           []string{"Endpoint might not be reachable"},
           []string{"Make sure the NATS endpoint is reachable"})

func NewDefault deprecated

func NewDefault(code string, ldescription ...string) *Error

Deprecated: NewDefault is deprecated, use New(...) instead.

func (*Error) Error

func (e *Error) Error() string

func (*Error) ErrorV2

func (e *Error) ErrorV2(additionalInfo interface{}) ErrorV2

type ErrorV2

type ErrorV2 struct {
	Code                 string
	Severity             Severity
	ShortDescription     []string
	LongDescription      []string
	ProbableCause        []string
	SuggestedRemediation []string
	AdditionalInfo       interface{}
	// Causes is the nested form NewV3 records: each probable cause with the
	// remediations that answer it. ProbableCause and SuggestedRemediation are
	// derived from it (FlattenCauses). Nil for New and NewV2 errors, and then
	// omitted from JSON, so their serialized form is unchanged.
	Causes []Cause `json:",omitempty"`
}

ErrorV2 addresses limitations of the Error struct defined above: There are different types of Errors. Each type of error contains different information. Short and Long Descriptions accept only strings and so they cannot contain structured information. e.g. The Validation Error information (instancePath, badValue etc.) cannot be contained in Error struct (or not in a structured way that the clients can make use of it)

ErrorV2 struct adds the ability to express all different types of errors. ErrorV2 is backwards compatible with Error struct

func AsErrorV2 added in v1.0.25

func AsErrorV2(err error) (ErrorV2, bool)

AsErrorV2 returns the MeshKit error in err's chain as an ErrorV2 value: the *ErrorV2 itself, or an *Error converted with no AdditionalInfo. ok is false when err carries no MeshKit error. It gives readers the raw description, cause and remediation lines (and Causes for NewV3) without the joining the Get* accessors apply.

func NewV2

func NewV2(code string, severity Severity, sdescription []string, ldescription []string, probablecause []string, remedy []string, additionalInfo interface{}) *ErrorV2

func NewV3 added in v1.0.25

func NewV3(code string, severity Severity, sdescription []string, ldescription []string, causes []Cause) *ErrorV2

NewV3 returns a MeshKit error whose probable causes each carry the remediations that answer them (meshery/meshkit#1138, meshery/schemas#1334).

The flat ProbableCause and SuggestedRemediation fields, and so GetCause, GetRemedy, Error() and every existing reader, are derived from causes with FlattenCauses. An empty ActionPolicy is stored as Manual. An unknown policy is kept as written, never coerced: ValidateCauses and errorutil reject it, and EffectivePolicy treats it as Manual so nothing runs by mistake.

As with New and NewV2, pass the code constant, and write every description, id, action and policy as a string literal (or a package-level Remediation variable for a shared remediation) so errorutil can export the definition.

Example:

var remReconnect = errors.Remediation{ID: "reconnect", Description: "Reconnect once the cluster is reachable.",
    Action: "connection.reconnect", ActionPolicy: errors.RequiresApproval}

errors.NewV3(ErrConnectCode, errors.Alert,
    []string{"Unable to connect to the cluster"},
    []string{"Meshery Server could not reach the cluster's API server"},
    []errors.Cause{
        {ID: "cluster-unreachable", Description: "The cluster's API server is not reachable.",
            Remediations: []errors.Remediation{
                {ID: "check-network", Description: "Check the network path to the API server."},
                remReconnect,
            }},
        {ID: "credentials-expired", Description: "The connection's credentials have expired.",
            Remediations: []errors.Remediation{
                {ID: "refresh-credentials", Description: "Refresh the credentials.",
                    Action: "connection.refresh-credentials", ActionPolicy: errors.Automatic},
                remReconnect,
            }},
    })

errorutil rejects description lists or causes not written as []string and []errors.Cause literals (a variable or nil, for example), and any description element that is not a string literal. To carry instance text such as err.Error(), append it to the returned error's LongDescription after NewV3 returns.

func (*ErrorV2) Error added in v0.8.54

func (e *ErrorV2) Error() string

type Remediation added in v1.0.25

type Remediation struct {
	// ID is stable once published: lowercase words joined by hyphens, for example `start-service`.
	ID string `json:"id"`
	// Description says what to do, written for a person.
	Description string `json:"description"`
	// Action optionally names what a client can run to apply the remediation,
	// as dot-separated lowercase words, for example `service.start`.
	Action string `json:"action,omitempty"`
	// ActionPolicy says whether a client may run Action on its own. Empty is Manual.
	// Automatic and RequiresApproval need an Action.
	ActionPolicy ActionPolicy `json:"actionPolicy,omitempty"`
}

Remediation is one way to answer a Cause, written in source for errors.NewV3.

Its JSON form is the schemas construct's Remediation (`id`, `description`, `action`, `actionPolicy`). It is a separate Go type from errorcode.Remediation only because the generated type uses pointers for its optional fields, and a pointer cannot be written as the string literal errorutil reads from source. ToSchema converts it.

A remediation that answers more than one cause is repeated under each cause with the same ID and identical fields; declare it once as a package-level variable and reference it from each cause.

func (Remediation) EffectivePolicy added in v1.0.25

func (r Remediation) EffectivePolicy() ActionPolicy

EffectivePolicy is the policy a client must act on: ActionPolicy when it is one of Automatic, RequiresApproval or Manual, and Manual otherwise, so an empty or unknown policy never runs anything.

func (Remediation) ToSchema added in v1.0.25

func (r Remediation) ToSchema() errorcode.Remediation

ToSchema returns the remediation as the schemas construct's Remediation. An empty ActionPolicy is written as Manual, and an empty Action is omitted.

type Severity

type Severity int

func GetSeverity

func GetSeverity(err error) Severity

func SeverityNamed added in v1.0.25

func SeverityNamed(name string) (Severity, bool)

SeverityNamed returns the MeshKit Severity whose constant is named name, as errorutil reads it from source (`Alert` for errors.Alert).

func (Severity) SchemaSeverity added in v1.0.25

func (s Severity) SchemaSeverity() (severity errorcode.ErrorSeverity, ok bool)

SchemaSeverity maps a MeshKit severity to the schemas construct's ErrorSeverity. None (and any unknown value) has no schema severity: ok is false.

Jump to

Keyboard shortcuts

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