faults

package module
v1.0.1 Latest Latest
Warning

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

Go to latest
Published: Mar 16, 2026 License: MIT Imports: 4 Imported by: 2

README

Faults

Package faults is an error-handling library that provides simple primitives to represent common failures within a system. Categorising errors simplifies error management and facilitates the propagation of failures across different boundaries, such as HTTP or gRPC.

This package is inspired by google.golang.org/genproto/googleapis/rpc/errdetails, which offers a similar set of primitives to describe standard problems encountered in systems.

The primary aim of this library is to establish a common language across different protocols, making it easier to propagate issues. Consider the typical scenario of a service that handles requests via a REST API and communicates with a SQL database. SQL databases have their own set of error codes, which often need to be manually mapped to their HTTP counterparts.

With faults, the essence of errors can be abstracted to more effectively communicate the nature of an error to the caller.

Benefits

Effective error handling is a critical component of robust software systems. It provides several key benefits:

  1. Improved Reliability: By categorising and managing errors consistently, systems can recover more gracefully from unexpected failures, leading to increased reliability.
  2. Enhanced Debugging: Clear and consistent error reporting allows developers to diagnose and fix issues more quickly. This reduces downtime and improves the overall stability of the system.
  3. Better User Experience: When errors are handled well, end users receive meaningful feedback instead of cryptic messages. This leads to a more user-friendly experience, as users can understand what went wrong and, in some cases, how to resolve the issue.
  4. Seamless Cross-Boundary Communication: In distributed systems, errors often need to be communicated across different services or protocols. A standardised approach to error handling ensures that errors are propagated correctly, maintaining the integrity of the system and reducing the likelihood of miscommunication between components.
  5. Easier Maintenance and Scalability: As systems grow, maintaining consistent error handling becomes increasingly important. Well-defined error primitives make it easier to extend and scale the system without introducing new points of failure.

By leveraging the faults library, developers can create more reliable, maintainable, and user-friendly systems that handle errors in a consistent and predictable manner.

Failure types

  1. Authentication
  2. Availability
  3. Bad
  4. Conflict
  5. Missing
  6. Permission
  7. Pre-condition
  8. Quota
  9. Unimplemented
Authentication

This error indicates that the request does not have valid authentication credentials for the operation.

func SensitiveOperation(ctx context.Context) error {
  user, ok := user.FromContext(ctx)
  if !ok {
    return faults.Unauthenticated
  }

  // Perform operation
  return nil
}
Availability

This error describes a temporary state that prevents the request from being fulfilled. The error can contain a delay that advises the caller when it is considered safe to retry.

func OutboundCall() error {
  res, err := http.Get("http://flaky-endpoint")
  if err != nil {
    return err
  }
  if res.StatusCode >= 500 {
    return faults.Unavailable(1 * time.Second)
  }

  // Process response

  return nil
}
Bad

This describes a violation in a client request, usually focusing on the syntactic aspect of the request. For example, a missing field or a name that is too short. It can also involve receiving an unexpected data format. This error is never safe to retry.

violations := []*faults.FieldViolation{
  {
    Field: "firstname",
    Description: "Field required",
  },
  {
    Field: "locality",
    Description: "Field required",
  },
}
err := faults.Bad(violations...)
Conflict

This error indicates that the request conflicts with the current state of the target resource. When this error occurs, the caller typically needs to restart a sequence of operations from the beginning.

func RegisterAccount(email string) error {
  acc, ok := accounts.LoadByEmail(email)
  if ok {
    return faults.Aborted(&faults.ConflictViolation{
      Resource:    fmt.Sprintf("account:%s", email),
      Description: "This email has already been registered",
    })
  }

  // Register account

  return nil
}
Missing

This error means the requested resource was not found. This is the equivalent of a 404 in HTTP.

func LoadAccount(id string) (Account, error) {
  acc, ok := accounts.Load(id)
  if !ok {
    return nil, faults.NotFound
  }

  return acc, nil
}
Permission

This error indicates that the caller does not have permission to execute the specified operation. It must not be used for rejections caused by exhausting some resource. It must also not be used if the caller cannot be identified.

func SensitiveResource(ctx context.Context) error {
  user, ok := user.FromContext(ctx)
  if !ok {
    return faults.Unauthenticated
  }
  if !user.IsAdmin() {
    return faults.PermissionDenied
  }

  // Perform operation

  return nil
}
Pre-condition

This error indicates that an operation was rejected because the system is not in a state required for the operation's execution. For example, a directory to be deleted may be non-empty, or an rmdir operation may be applied to a non-directory.

func LoginAccount(email, hash string) error {
  acc, ok := accounts.LoadByEmail(email)
  if !ok {
      return faults.FailedPrecondition(&faults.PreconditionViolation{
        Type:        "account",
        Subject:     fmt.Sprintf("account:%s", email),
        Description: "Account does not exist. Please register first",
      })
  }

  // Authenticate..

  return nil
}
Quota

This error describes a failure in a quota check.

For example, if a daily limit is exceeded for the calling project, a service could respond with this error, including details such as the project ID and a description of the exceeded quota limit.

func ExampleHandler(w http.ResponseWriter, r *http.Request) {
  if quotaExceeded() {
    err := faults.ResourceExhausted(&faults.QuotaViolation{
      Subject:     "clientip:<ip address of client>",
      Description: "Daily Limit for read operations exceeded",
    })

    http.Error(w, err.Error(), http.StatusTooManyRequests)
    return
  }

  // Handle the request...
}
Unimplemented

This indicates the operation is not implemented or not supported.

func NewFeature() error {
  return faults.Unimplemented
}

Litmus test

A litmus test that may help a service implementor in deciding between a pre-condition failure, a conflict, and an unavailability error.

  • Use faults.Unavailable if the client can retry just the failing call.
  • Use faults.Aborted if the client should retry at a higher-level (e.g., restarting a read-modify-write sequence).
  • Use faults.FailedPrecondition if the client should not retry until the system state has been explicitly fixed. E.g., if an "rmdir" fails because the directory is non-empty, FailedPrecondition should be returned since the client should not retry unless they have first fixed up the directory by deleting files from it.
  • Use faults.FailedPrecondition if the client performs conditional REST Get/Update/Delete on a resource and the resource on the server does not match the condition. E.g., conflicting read-modify-write on the same resource.

Error chain

Go 1.13 introduces the concept of wrapping errors to trace back to the root cause of an issue. An error can be wrapped in this way: fmt.Errorf("wrapped error: %w", err).

With faults, errors can also be wrapped easily by calling the prefix faults.With*. Once wrapped, an error will be categorised, but the underlying error can still be retrieved.

Example:

_, err := os.Stat(path)
if os.IsNotExist(err) {
  return faults.WithNotFound(err)
}

// Carry on...

Design

This repository was initially hosted at github.com/deixis/errors but has since been renamed to faults. The original concept was to fully wrap the standard errors package, similar to github.com/pkg/errors. This approach allowed developers to simply rename their errors import and immediately benefit from enhanced functionality while maintaining the familiar API.

However, this approach is no longer ideal. Go has since introduced native support for error wrapping within the standard errors package. Moreover, using a custom errors package can impede linters and static analysis tools from accurately detecting the misuse of functions like errors.Is or errors.As.

Consequently, this new version has removed all standard error calls and now focuses exclusively on providing specialised primitives to help developers categorise errors more effectively.

Disclaimer

The code snippets provided above are intended to demonstrate how to use the different primitives. The examples are purposefully oversimplified and should not be used as-is in production environments.

Documentation

Overview

Package `faults` is an error handling library with simple primitives that allow to represent typical failures in a system. Categorising errors simplify error management and allow to propagate a failure across boundaries more easily, such as HTTP or gRPC.

Note: This package is an almost identical copy of `github.com/deixis/errors`, which is itself an almost identical copy of `google.golang.org/grpc/status`. The reason for the name change to `faults` is to avoid issues with linters that don't validate `errors.Is` and `errors.As` issues when the package is not the standard `errors` package.

Index

Constants

This section is empty.

Variables

View Source
var (
	// PermissionDenied indicates the caller does not have permission to
	// execute the specified operation. It must not be used for rejections
	// caused by exhausting some resource (use ResourceExhausted
	// instead for those errors). It must not be
	// used if the caller cannot be identified (use Unauthenticated
	// instead for those errors).
	PermissionDenied error = &PermissionFailure{}

	// Unauthenticated indicates the request does not have valid
	// authentication credentials for the operation.
	Unauthenticated error = &AuthenticationFailure{}

	// NotFound means some requested entity (e.g., file or directory) was
	// not found.
	NotFound error = &MissingFailure{}

	// Unimplemented indicates the operation is not implemented or not supported
	Unimplemented error = &UnimplementedFailure{}
)

Functions

func Aborted

func Aborted(violations ...*ConflictViolation) error

Aborted indicates the operation was aborted, typically due to a concurrency issue like sequencer check failures, transaction aborts, etc.

See litmus test above for deciding between FailedPrecondition, Aborted, and Unavailable.

func Bad

func Bad(violations ...*FieldViolation) error

Bad indicates client specified an invalid argument. Note that this differs from FailedPrecondition. It indicates arguments that are problematic regardless of the state of the system (e.g., a malformed file name).

func FailedPrecondition

func FailedPrecondition(violations ...*PreconditionViolation) error

FailedPrecondition indicates operation was rejected because the system is not in a state required for the operation's execution. For example, directory to be deleted may be non-empty, an rmdir operation is applied to a non-directory, etc.

A litmus test that may help a service implementor in deciding between FailedPrecondition, Aborted, and Unavailable:

(a) Use Unavailable if the client can retry just the failing call.
(b) Use Aborted if the client should retry at a higher-level
    (e.g., restarting a read-modify-write sequence).
(c) Use FailedPrecondition if the client should not retry until
    the system state has been explicitly fixed. E.g., if an "rmdir"
    fails because the directory is non-empty, FailedPrecondition
    should be returned since the client should not retry unless
    they have first fixed up the directory by deleting files from it.
(d) Use FailedPrecondition if the client performs conditional
    REST Get/Update/Delete on a resource and the resource on the
    server does not match the condition. E.g., conflicting
    read-modify-write on the same resource.

func IsAborted

func IsAborted(err error) bool

func IsBad

func IsBad(err error) bool

func IsFailedPrecondition

func IsFailedPrecondition(err error) bool

func IsNotFound

func IsNotFound(err error) bool

func IsPermissionDenied

func IsPermissionDenied(err error) bool

func IsResourceExhausted

func IsResourceExhausted(err error) bool

func IsUnauthenticated

func IsUnauthenticated(err error) bool

func IsUnavailable

func IsUnavailable(err error) bool

func IsUnimplemented

func IsUnimplemented(err error) bool

func ResourceExhausted

func ResourceExhausted(violations ...*QuotaViolation) error

ResourceExhausted indicates some resource has been exhausted, perhaps a per-user quota, or perhaps the entire file system is out of space.

func Unavailable

func Unavailable(retryDelay time.Duration) error

Unavailable indicates the service is currently unavailable. This is a most likely a transient condition and may be corrected by retrying with a backoff.

See litmus test above for deciding between FailedPrecondition, Aborted, and Unavailable.

func WithAborted

func WithAborted(parent error, violations ...*ConflictViolation) error

WithAborted wraps `parent` with a `ConflictFailure`

func WithBad

func WithBad(parent error, violations ...*FieldViolation) error

WithBad wraps `parent` with a `BadRequest`

func WithFailedPrecondition

func WithFailedPrecondition(parent error, violations ...*PreconditionViolation) error

WithFailedPrecondition wraps `parent` with a `PreconditionFailure`

func WithNotFound

func WithNotFound(parent error) error

WithNotFound wraps `parent` with a `MissingFailure`

func WithPermissionDenied

func WithPermissionDenied(parent error) error

WithPermissionDenied wraps `parent` with a `PermissionFailure`

func WithResourceExhausted

func WithResourceExhausted(parent error, violations ...*QuotaViolation) error

WithResourceExhausted wraps `parent` with a `QuotaFailure`

func WithUnauthenticated

func WithUnauthenticated(parent error) error

WithUnauthenticated wraps `parent` with an `AuthenticationFailure`

func WithUnavailable

func WithUnavailable(parent error, retryDelay time.Duration) error

WithUnavailable wraps `parent` with an `AvailabilityFailure`

func WithUnimplemented

func WithUnimplemented(parent error) error

WithUnimplemented wraps `parent` with an `UnimplementedFailure`

Types

type AuthenticationFailure

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

func AsUnauthenticated

func AsUnauthenticated(err error) (*AuthenticationFailure, bool)

func (*AuthenticationFailure) Error

func (e *AuthenticationFailure) Error() string

func (*AuthenticationFailure) Is

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

func (*AuthenticationFailure) Unwrap

func (e *AuthenticationFailure) Unwrap() error

type AvailabilityFailure

type AvailabilityFailure struct {
	RetryInfo RetryInfo
	// contains filtered or unexported fields
}

AvailabilityFailure indicates that the service is currently unavailable. This is most likely a transient condition and may be corrected by retrying.

func AsUnavailable

func AsUnavailable(err error) (*AvailabilityFailure, bool)

func (*AvailabilityFailure) Error

func (e *AvailabilityFailure) Error() string

func (*AvailabilityFailure) Is

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

func (*AvailabilityFailure) Unwrap

func (e *AvailabilityFailure) Unwrap() error

type BadRequest

type BadRequest struct {

	// Describes all violations in a client request.
	Violations []*FieldViolation
	// contains filtered or unexported fields
}

Describes violations in a client request. This error type focuses on the syntactic aspects of the request.

func AsBad

func AsBad(err error) (*BadRequest, bool)

func (*BadRequest) Error

func (e *BadRequest) Error() string

func (*BadRequest) Is

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

func (*BadRequest) Unwrap

func (e *BadRequest) Unwrap() error

type ConflictFailure

type ConflictFailure struct {

	// Describes all violations in a client request.
	Violations []*ConflictViolation
	// contains filtered or unexported fields
}

A ConflictFailure indicates that the request conflicts with the current state of the target resource.

When this error occurs, the caller must usually restart a sequence of operations from the beginning.

func AsAborted

func AsAborted(err error) (*ConflictFailure, bool)

func (*ConflictFailure) Error

func (e *ConflictFailure) Error() string

func (*ConflictFailure) Is

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

func (*ConflictFailure) Unwrap

func (e *ConflictFailure) Unwrap() error

type ConflictViolation

type ConflictViolation struct {
	// resource on which the conflict occurred.
	// For example, "user:<uuid>" or "billing/invoice:<uuid>".
	Resource string
	// A description of why the request element is bad.
	Description string
}

func (*ConflictViolation) String

func (v *ConflictViolation) String() string

type FieldViolation

type FieldViolation struct {
	// A path leading to a field in the request body. The value will be a
	// sequence of dot-separated identifiers that identify a protocol buffer
	// field. E.g., "field_violations.field" would identify this field.
	Field string
	// A description of why the request element is bad.
	Description string
}

A message type used to describe a single bad request field.

func (*FieldViolation) String

func (v *FieldViolation) String() string

type MissingFailure

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

func AsNotFound

func AsNotFound(err error) (*MissingFailure, bool)

func (*MissingFailure) Error

func (e *MissingFailure) Error() string

func (*MissingFailure) Is

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

func (*MissingFailure) Unwrap

func (e *MissingFailure) Unwrap() error

type PermissionFailure

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

func AsPermissionDenied

func AsPermissionDenied(err error) (*PermissionFailure, bool)

func (*PermissionFailure) Error

func (e *PermissionFailure) Error() string

func (*PermissionFailure) Is

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

func (*PermissionFailure) Unwrap

func (e *PermissionFailure) Unwrap() error

type PreconditionFailure

type PreconditionFailure struct {

	// Describes all precondition violations.
	Violations []*PreconditionViolation
	// contains filtered or unexported fields
}

Describes what preconditions have failed.

For example, if an RPC failed because it required the Terms of Service to be acknowledged, it could list the terms of service violation in the PreconditionFailure message.

func AsFailedPrecondition

func AsFailedPrecondition(err error) (*PreconditionFailure, bool)

func (*PreconditionFailure) Error

func (e *PreconditionFailure) Error() string

func (*PreconditionFailure) Is

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

func (*PreconditionFailure) Unwrap

func (e *PreconditionFailure) Unwrap() error

type PreconditionViolation

type PreconditionViolation struct {
	// The type of PreconditionFailure. We recommend using a service-specific
	// enum type to define the supported precondition violation types. For
	// example, "TOS" for "Terms of Service violation".
	Type string
	// The subject, relative to the type, that failed.
	// For example, "google.com/cloud" relative to the "TOS" type would
	// indicate which terms of service is being referenced.
	Subject string
	// A description of how the precondition failed. Developers can use this
	// description to understand how to fix the failure.
	//
	// For example: "Terms of service not accepted".
	Description string
}

A message type used to describe a single precondition failure.

func (*PreconditionViolation) String

func (v *PreconditionViolation) String() string

type QuotaFailure

type QuotaFailure struct {

	// Describes all quota violations.
	Violations []*QuotaViolation
	// contains filtered or unexported fields
}

Describes how a quota check failed.

For example if a daily limit was exceeded for the calling project, a service could respond with a QuotaFailure detail containing the project id and the description of the quota limit that was exceeded. If the calling project hasn't enabled the service in the developer console, then a service could respond with the project id and set `service_disabled` to true.

Also see RetryDetail and Help types for other details about handling a

func AsResourceExhausted

func AsResourceExhausted(err error) (*QuotaFailure, bool)

func (*QuotaFailure) Error

func (e *QuotaFailure) Error() string

func (*QuotaFailure) Is

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

func (*QuotaFailure) Unwrap

func (e *QuotaFailure) Unwrap() error

type QuotaViolation

type QuotaViolation struct {
	// The subject on which the quota check failed.
	// For example, "clientip:<ip address of client>" or "project:<Google
	// developer project id>".
	Subject string
	// A description of how the quota check failed. Clients can use this
	// description to find more about the quota configuration in the service's
	// public documentation, or find the relevant quota limit to adjust through
	// developer console.
	//
	// For example: "Service disabled" or "Daily Limit for read operations
	// exceeded".
	Description string
}

A message type used to describe a single quota violation. For example, a daily quota or a custom quota that was exceeded.

func (*QuotaViolation) String

func (v *QuotaViolation) String() string

type RetryInfo

type RetryInfo struct {
	// Clients should wait at least this long between retrying the same request.
	RetryDelay time.Duration
}

RetryInfo describes when the clients can retry a failed request. Clients could ignore the recommendation here or retry when this information is missing from error responses.

It's always recommended that clients should use exponential backoff when retrying.

Clients should wait until `retry_delay` amount of time has passed since receiving the error response before retrying. If retrying requests also fail, clients should use an exponential backoff scheme to gradually increase the delay between retries based on `retry_delay`, until either a maximum number of retires have been reached or a maximum retry delay cap has been reached.

type UnimplementedFailure

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

func AsUnimplemented

func AsUnimplemented(err error) (*UnimplementedFailure, bool)

func (*UnimplementedFailure) Error

func (e *UnimplementedFailure) Error() string

func (*UnimplementedFailure) Is

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

func (*UnimplementedFailure) Unwrap

func (e *UnimplementedFailure) Unwrap() error

Jump to

Keyboard shortcuts

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