errors

package
v0.0.2 Latest Latest
Warning

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

Go to latest
Published: Nov 16, 2026 License: AGPL-3.0 Imports: 10 Imported by: ? modules, 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 creates and inspects typed errors. It replaces the standard library's errors package and fmt.Errorf in a codebase: Is, As, AsType and Join call the standard library, so callers import only this package.

Every error has a Type, which says what the caller can do about it, a Code, which identifies the failure, and a message. It records the stack where it was created.

if id == "" {
	return errors.New(errors.TypeInvalidInput, CodeRunIDMissing, "id is required")
}

rows, err := db.QueryContext(ctx, query)
if err != nil {
	return errors.Wrapf(err, errors.TypeInternal, CodeRunsListFailed, "list runs of %s", orgID)
}

Types and codes

Pick the type for what the caller can do: TypeInvalidInput for bad input, TypeNotFound for something that doesn't exist, TypeInternal for a dependency that failed, and so on. A type carries the HTTP status and retryability that HTTPStatus and IsRetryable report. A package declares types of its own with MustNewType, and the codes of its errors with MustNewCode:

var (
	TypeLicenseUnavailable = errors.MustNewType("license-unavailable", http.StatusUnavailableForLegalReasons, false)
	CodeLicenseExpired     = errors.MustNewCode("license_expired")
)

Don't declare sentinel errors. An error created at init has a useless stack trace. Return a fresh error and branch on its type or code instead, with TypeOf, CodeOf, Ast, Asc, IsNotFound and the other Is functions.

Wrapping

Wrap and Wrapf add a type, a code and a short context to an error from a dependency. The text of the result is "context: cause", and Is and As still reach the cause. Messages say "expected", never "want", and never contain a secret such as a token or a password.

Lookups use the first typed error in the chain, so an error wrapped by another library or joined with Join keeps its type. An error without one is untyped: its type is TypeUnknown and its code CodeUnknown.

Details for API responses

New, Newf, Wrap, Wrapf and WithAdditionalf return an error with methods that add details for an API response. Each returns a copy and leaves the original unchanged:

  • WithURL sets a documentation URL.
  • WithAdditional adds an additional: a detail such as one invalid field, with suggestions of its own.
  • WithSuggestions sets suggestions for the error as a whole.
  • WithRetryAfter sets how long the client should wait before retrying.
  • WithStacktrace replaces the recorded stack, such as with the stack of a recovered panic.

AsException puts them in an API response, and the error's methods URL, Suggestions, RetryAfter and Stacktrace read them back, as Type, Code and Message read the rest. Wrapping keeps the cause's additionals, suggestions and retry delay, but not its URL.

Logging

Attr adds an error to a log/slog record as exception.type, exception.code, exception.message and exception.stacktrace:

logger.ErrorContext(ctx, "cannot send notification", errors.Attr(err))

HTTP

AsException converts an error to the body of an API response, HTTPStatus picks its status code, and RetryAfterOf gives the Retry-After delay. TypeFromHTTPStatus goes the other way, for errors read from another service's response.

Linting

To keep the standard library's errors package and fmt.Errorf out of a codebase, add this to .golangci.yml:

linters:
  enable:
    - depguard
    - forbidigo
  settings:
    depguard:
      rules:
        noerrors:
          files:
            - $all
          deny:
            - pkg: errors
              desc: Use github.com/SigNoz/baseplate.go/errors instead.
    forbidigo:
      forbid:
        - pattern: fmt.Errorf
          msg: Use github.com/SigNoz/baseplate.go/errors instead.
Example
package main

import (
	"fmt"
	"io/fs"
	"net/http"

	"github.com/SigNoz/baseplate.go/errors"
)

// A package declares the codes and the types of its own errors.
var CodeBackupMissing = errors.MustNewCode("backup_missing")

func main() {
	err := errors.Wrapf(fs.ErrNotExist, errors.TypeNotFound, CodeBackupMissing, "no backup of %s", "db_1")

	_, _ = fmt.Println(err)
	_, _ = fmt.Println(errors.TypeOf(err), errors.CodeOf(err))
	_, _ = fmt.Println(errors.IsNotFound(err), errors.Is(err, fs.ErrNotExist))
}
Output:
no backup of db_1: file does not exist
not-found backup_missing
true true

Index

Examples

Constants

This section is empty.

Variables

View Source
var (
	// TypeUnknown is what [TypeOf] returns for an untyped error. Don't create
	// errors with it.
	TypeUnknown          = Type{/* contains filtered or unexported fields */}
	TypeInvalidInput     = Type{/* contains filtered or unexported fields */}
	TypeUnauthenticated  = Type{/* contains filtered or unexported fields */}
	TypeForbidden        = Type{/* contains filtered or unexported fields */}
	TypeNotFound         = Type{/* contains filtered or unexported fields */}
	TypeMethodNotAllowed = Type{/* contains filtered or unexported fields */}
	TypeConflict         = Type{/* contains filtered or unexported fields */}
	TypeTooManyRequests  = Type{/* contains filtered or unexported fields */}
	// TypeCanceled maps to nginx's non-standard 499 Client Closed Request.
	TypeCanceled    = Type{/* contains filtered or unexported fields */}
	TypeTimeout     = Type{/* contains filtered or unexported fields */}
	TypeUnsupported = Type{/* contains filtered or unexported fields */}
	TypeUnavailable = Type{/* contains filtered or unexported fields */}
	TypeInternal    = Type{/* contains filtered or unexported fields */}
	// TypeFatal is an unrecoverable failure, such as a recovered panic.
	TypeFatal = Type{/* contains filtered or unexported fields */}
)

The base types, one per thing a caller can do about an error. A package declares more with NewType or MustNewType.

View Source
var (
	// CodeUnknown is what [CodeOf] returns for an untyped error, and the code
	// [WithAdditionalf] gives one. Declare a package's own codes for the errors
	// it creates.
	CodeUnknown = Code{"unknown"}
)

Functions

func As

func As(err error, target any) bool

As calls errors.As from the standard library.

func AsType

func AsType[E error](err error) (E, bool)

AsType calls errors.AsType from the standard library.

func AsURLValues

func AsURLValues(err error) url.Values

AsURLValues returns err's code, message and url, and its additionals as a JSON array under errors, for the query string of a redirect that reports an error. It reads err the way AsException does.

func Asc

func Asc(err error, c Code) bool

Asc reports whether the code of err, as returned by CodeOf, is c.

func Ast

func Ast(err error, t Type) bool

Ast reports whether the type of err, as returned by TypeOf, is t.

func Attr

func Attr(err error) slog.Attr

Attr returns err as an "exception" group for log/slog with type, code, message and stacktrace attributes, which a text handler writes as exception.type=not-found and so on. The message is err's full text. An untyped error gives its Go type and message only, and a nil err gives an empty group, which handlers drop.

Example

The handler drops the time and the stack trace to keep the output stable.

package main

import (
	"log/slog"
	"net/http"
	"os"

	"github.com/SigNoz/baseplate.go/errors"
)

// A package declares the codes and the types of its own errors.
var CodeBackupMissing = errors.MustNewCode("backup_missing")

func main() {
	logger := slog.New(slog.NewTextHandler(os.Stdout, &slog.HandlerOptions{
		ReplaceAttr: func(groups []string, a slog.Attr) slog.Attr {
			if a.Key == slog.TimeKey || a.Key == "stacktrace" {
				return slog.Attr{}
			}

			return a
		},
	}))

	logger.Error("cannot restore", errors.Attr(errors.New(errors.TypeNotFound, CodeBackupMissing, "no backup of db_1")))
}
Output:
level=ERROR msg="cannot restore" exception.type=not-found exception.code=backup_missing exception.message="no backup of db_1"

func HTTPStatus

func HTTPStatus(err error) int

HTTPStatus returns the HTTP status code of the type of the first typed error in err's chain, which NewType sets for a package's own types. The base types map to the matching 4xx and 5xx statuses, with TypeCanceled as nginx's 499. TypeInternal, TypeFatal, TypeUnknown and an untyped error are 500.

Example
package main

import (
	"context"
	"fmt"
	"net/http"

	"github.com/SigNoz/baseplate.go/errors"
)

// A package declares the codes and the types of its own errors.
var (
	CodeBackupMissing = errors.MustNewCode("backup_missing")

	CodeLicenseExpired = errors.MustNewCode("license_expired")

	TypeLicenseUnavailable = errors.MustNewType("license-unavailable", http.StatusUnavailableForLegalReasons, false)
)

func main() {
	_, _ = fmt.Println(errors.HTTPStatus(errors.New(errors.TypeNotFound, CodeBackupMissing, "no backup of db_1")))
	_, _ = fmt.Println(errors.HTTPStatus(errors.New(TypeLicenseUnavailable, CodeLicenseExpired, "license expired")))
	_, _ = fmt.Println(errors.HTTPStatus(context.DeadlineExceeded))
}
Output:
404
451
500

func Is

func Is(err, target error) bool

Is calls errors.Is from the standard library.

func IsConflict

func IsConflict(err error) bool

IsConflict reports whether the type of err is TypeConflict.

func IsForbidden

func IsForbidden(err error) bool

IsForbidden reports whether the type of err is TypeForbidden.

func IsNotFound

func IsNotFound(err error) bool

IsNotFound reports whether the type of err is TypeNotFound.

func IsRetryable

func IsRetryable(err error) bool

IsRetryable reports whether retrying the operation that returned err may succeed, as the type of err says. It is false for nil. Of the base types, TypeInvalidInput, TypeUnauthenticated, TypeForbidden, TypeMethodNotAllowed, TypeConflict, TypeCanceled and TypeUnsupported aren't retryable. An untyped error is retryable, because its outcome is unknown.

Example
package main

import (
	"context"
	"fmt"
	"net/http"

	"github.com/SigNoz/baseplate.go/errors"
)

// A package declares the codes and the types of its own errors.
var (
	CodeFilterInvalid = errors.MustNewCode("filter_invalid")

	CodeRateLimited = errors.MustNewCode("rate_limited")
)

func main() {
	_, _ = fmt.Println(errors.IsRetryable(errors.New(errors.TypeTooManyRequests, CodeRateLimited, "rate limited")))
	_, _ = fmt.Println(errors.IsRetryable(errors.New(errors.TypeInvalidInput, CodeFilterInvalid, "invalid filter")))
	_, _ = fmt.Println(errors.IsRetryable(context.DeadlineExceeded))
}
Output:
true
false
true

func IsUnauthenticated

func IsUnauthenticated(err error) bool

IsUnauthenticated reports whether the type of err is TypeUnauthenticated.

func IsUnavailable

func IsUnavailable(err error) bool

IsUnavailable reports whether the type of err is TypeUnavailable.

func Join

func Join(errs ...error) error

Join calls errors.Join from the standard library.

func MessageOf

func MessageOf(err error) string

MessageOf returns the message, without its cause, of the first typed error in err's chain. It returns err's full text when err is untyped, and "" when err is nil.

Example
package main

import (
	"fmt"
	"io/fs"
	"net/http"

	"github.com/SigNoz/baseplate.go/errors"
)

// A package declares the codes and the types of its own errors.
var CodeUserReadFailed = errors.MustNewCode("user_read_failed")

func main() {
	err := errors.Wrap(fs.ErrClosed, errors.TypeInternal, CodeUserReadFailed, "cannot read user")

	_, _ = fmt.Println(errors.MessageOf(err))
	_, _ = fmt.Println(errors.MessageOf(fs.ErrClosed))
}
Output:
cannot read user
file already closed

func New

func New(t Type, c Code, message string) *base

New returns an error of type t and code c with message, and records the stack where it is called.

Example
package main

import (
	"fmt"
	"net/http"

	"github.com/SigNoz/baseplate.go/errors"
)

// A package declares the codes and the types of its own errors.
var (
	CodeLicenseExpired = errors.MustNewCode("license_expired")

	TypeLicenseUnavailable = errors.MustNewType("license-unavailable", http.StatusUnavailableForLegalReasons, false)
)

func main() {
	err := errors.New(TypeLicenseUnavailable, CodeLicenseExpired, "license expired on 2026-10-01")

	_, _ = fmt.Println(err)
	_, _ = fmt.Println(errors.Asc(err, CodeLicenseExpired), errors.HTTPStatus(err), errors.IsRetryable(err))
}
Output:
license expired on 2026-10-01
true 451 false
Example (Details)
package main

import (
	"fmt"
	"net/http"

	"github.com/SigNoz/baseplate.go/errors"
)

// A package declares the codes and the types of its own errors.
var CodeFilterInvalid = errors.MustNewCode("filter_invalid")

func main() {
	err := errors.New(errors.TypeInvalidInput, CodeFilterInvalid, "invalid filter").
		WithURL("https://signoz.io/docs/filters").
		WithAdditional("operator ~ is unsupported").
		WithAdditional("key servce is unknown", "did you mean: service").
		WithSuggestions("check the filter syntax")

	_, _ = fmt.Println(err.Message())
	_, _ = fmt.Println(err.URL())
	_, _ = fmt.Println(errors.AsException(err).Errors)
	_, _ = fmt.Println(err.Suggestions())
}
Output:
invalid filter
https://signoz.io/docs/filters
[{operator ~ is unsupported []} {key servce is unknown [did you mean: service]}]
[check the filter syntax]

func Newf

func Newf(t Type, c Code, format string, args ...any) *base

Newf is New with a message formatted as in fmt.Sprintf.

func RetryAfterOf

func RetryAfterOf(err error) time.Duration

RetryAfterOf returns the retry delay of the first typed error in err's chain, or zero when there is none or err is nil.

func WithAdditionalf

func WithAdditionalf(err error, format string, args ...any) *base

WithAdditionalf wraps err with an additional formatted as in fmt.Sprintf, leaving its text and message unchanged. It keeps the type, code, URL and stack trace of the first typed error in err's chain. An untyped err becomes TypeInternal and CodeUnknown, with the stack where WithAdditionalf is called.

Example

An untyped error becomes TypeInternal and CodeUnknown, and its text stays the same.

package main

import (
	"fmt"
	"io/fs"

	"github.com/SigNoz/baseplate.go/errors"
)

func main() {
	err := errors.WithAdditionalf(fs.ErrPermission, "cannot delete user %s", "u_1")

	_, _ = fmt.Println(err)
	_, _ = fmt.Println(errors.TypeOf(err), errors.CodeOf(err))
	_, _ = fmt.Println(errors.AsException(err).Errors)
}
Output:
permission denied
internal unknown
[{cannot delete user u_1 []}]

func Wrap

func Wrap(cause error, t Type, c Code, message string) *base

Wrap returns an error of type t and code c that wraps cause with message, and records the stack where it is called. Its text is "message: cause". It keeps the additionals, suggestions and retry delay of the first typed error in cause's chain, but not its URL.

Example
package main

import (
	"fmt"
	"net/http"
	"time"

	"github.com/SigNoz/baseplate.go/errors"
)

// A package declares the codes and the types of its own errors.
var (
	CodeLogsQueryFailed = errors.MustNewCode("logs_query_failed")
	CodeRateLimited     = errors.MustNewCode("rate_limited")
)

func main() {
	cause := errors.New(errors.TypeTooManyRequests, CodeRateLimited, "rate limited").WithRetryAfter(2 * time.Second)

	err := errors.Wrap(cause, errors.TypeUnavailable, CodeLogsQueryFailed, "cannot query logs")

	_, _ = fmt.Println(err)
	_, _ = fmt.Println(err.Message())
	_, _ = fmt.Println(errors.TypeOf(err), err.RetryAfter())
}
Output:
cannot query logs: rate limited
cannot query logs
unavailable 2s

func Wrapf

func Wrapf(cause error, t Type, c Code, format string, args ...any) *base

Wrapf is Wrap with a message formatted as in fmt.Sprintf.

Types

type Code

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

Code identifies one failure for machines, more finely than its type, such as "license_expired" or "SecretNotFound". Each package declares its own codes with NewCode or MustNewCode. Compare codes with ==.

func CodeOf

func CodeOf(err error) Code

CodeOf returns the code of the first typed error in err's chain, or CodeUnknown when there is none or err is nil.

func MustNewCode

func MustNewCode(s string) Code

MustNewCode is NewCode that panics on an invalid code, for declaring codes in package-level vars.

func NewCode

func NewCode(s string) (Code, error)

NewCode returns the code s. It accepts a letter followed by letters, digits and underscores, so both snake_case and CamelCase work, and returns a TypeInvalidInput error for anything else.

Example
package main

import (
	"fmt"

	"github.com/SigNoz/baseplate.go/errors"
)

func main() {
	_, err := errors.NewCode("not-found")

	_, _ = fmt.Println(err)
}
Output:
code "not-found" is invalid, expected a letter followed by letters, digits or underscores

func (Code) MarshalText

func (c Code) MarshalText() ([]byte, error)

MarshalText returns the code, as String does.

func (Code) String

func (c Code) String() string

String returns the code as it was declared.

func (*Code) UnmarshalText

func (c *Code) UnmarshalText(text []byte) error

UnmarshalText sets the code from text, which must be valid for NewCode.

type Exception

type Exception struct {
	Type        string                `json:"type" required:"true" nullable:"false"`
	Code        string                `json:"code" required:"true" nullable:"false"`
	Message     string                `json:"message" required:"true" nullable:"false"`
	URL         string                `json:"url,omitempty" required:"false"`
	Errors      []ExceptionAdditional `json:"errors" required:"true" nullable:"false"` // The error's additionals.
	Retry       *ExceptionRetry       `json:"retry,omitempty" required:"false"`
	Suggestions []string              `json:"suggestions" required:"true" nullable:"false"`
}

Exception is the public form of an error, as written in the error body of an API response. Errors and Suggestions are never null.

func AsException

func AsException(err error) *Exception

AsException converts err to its public form, built from the first typed error in its chain. The message is that error's own message without its cause, so wrapped causes don't reach the client. An untyped err has TypeUnknown, CodeUnknown and its full text as the message. Don't pass a nil err.

Example
package main

import (
	"context"
	"encoding/json"
	"fmt"
	"net/http"
	"time"

	"github.com/SigNoz/baseplate.go/errors"
)

// A package declares the codes and the types of its own errors.
var CodeLogsQueryFailed = errors.MustNewCode("logs_query_failed")

func main() {
	err := errors.Wrap(context.Canceled, errors.TypeCanceled, CodeLogsQueryFailed, "query canceled").
		WithRetryAfter(time.Second)

	body, marshalErr := json.Marshal(errors.AsException(err))
	if marshalErr != nil {
		panic(marshalErr)
	}

	_, _ = fmt.Println(string(body))
}
Output:
{"type":"canceled","code":"logs_query_failed","message":"query canceled","errors":[],"retry":{"delay":1000000000},"suggestions":[]}

type ExceptionAdditional

type ExceptionAdditional struct {
	Message     string   `json:"message" required:"true" nullable:"false"`
	Suggestions []string `json:"suggestions" required:"true" nullable:"false"`
}

ExceptionAdditional is one additional of an Exception.

type ExceptionRetry

type ExceptionRetry struct {
	Delay time.Duration `json:"delay" required:"true" nullable:"false"` // In nanoseconds.
}

ExceptionRetry tells the client when to retry, and is set on an Exception only when the error has a retry delay.

type Type

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

Type says what a caller can do about an error. It carries the HTTP status that HTTPStatus returns and whether IsRetryable reports that a retry may succeed. Compare types with ==. A type marshals to its name but can't be decoded from it, because the name doesn't carry the status or retryability.

func MustNewType

func MustNewType(name string, status int, retryable bool) Type

MustNewType is NewType that panics on an invalid type, for declaring types in package-level vars.

func NewType

func NewType(name string, status int, retryable bool) (Type, error)

NewType returns a type for a package's own errors, such as "license-unavailable". The name must be kebab-case, and status an HTTP error status from 400 to 599. Retryable says whether retrying the operation that failed may succeed without a change to the request, credentials or system. It returns a TypeInvalidInput error for an invalid name or status.

Example
package main

import (
	"fmt"
	"net/http"

	"github.com/SigNoz/baseplate.go/errors"
)

func main() {
	typ, err := errors.NewType("license-unavailable", http.StatusUnavailableForLegalReasons, false)
	if err != nil {
		panic(err)
	}

	_, _ = fmt.Println(typ)
}
Output:
license-unavailable

func TypeFromHTTPStatus

func TypeFromHTTPStatus(status int) Type

TypeFromHTTPStatus returns the base type for an HTTP status code, the reverse of HTTPStatus, for building an error from another service's response. An unmapped 5xx status is TypeInternal, and any other unmapped status is TypeUnknown.

Example
package main

import (
	"fmt"
	"net/http"

	"github.com/SigNoz/baseplate.go/errors"
)

func main() {
	_, _ = fmt.Println(errors.TypeFromHTTPStatus(http.StatusTooManyRequests))
	_, _ = fmt.Println(errors.TypeFromHTTPStatus(http.StatusBadGateway))
}
Output:
too-many-requests
internal

func TypeOf

func TypeOf(err error) Type

TypeOf returns the type of the first typed error in err's chain, or TypeUnknown when there is none or err is nil.

Example
package main

import (
	"context"
	"fmt"
	"net/http"

	"github.com/SigNoz/baseplate.go/errors"
)

// A package declares the codes and the types of its own errors.
var (
	CodeLicenseExpired = errors.MustNewCode("license_expired")

	TypeLicenseUnavailable = errors.MustNewType("license-unavailable", http.StatusUnavailableForLegalReasons, false)
)

func main() {
	typed := errors.Join(context.Canceled, errors.New(TypeLicenseUnavailable, CodeLicenseExpired, "license expired"))
	untyped := context.DeadlineExceeded

	_, _ = fmt.Println(errors.TypeOf(typed))
	_, _ = fmt.Println(errors.TypeOf(untyped))
}
Output:
license-unavailable
unknown

func (Type) MarshalText

func (t Type) MarshalText() ([]byte, error)

MarshalText returns the type's name, as String does.

func (Type) String

func (t Type) String() string

String returns the type's name, such as "not-found".

Jump to

Keyboard shortcuts

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