apperr

package module
v0.0.0-...-ed11039 Latest Latest
Warning

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

Go to latest
Published: Oct 28, 2022 License: Apache-2.0 Imports: 5 Imported by: 2

README

🗑 apperr

apperr provides a unified application error generation interface. Errors can be localized and converted to GRPC, Twirp, HTTP, etc. equivalents

Go Reference

Installation

To install apperr, simly run:

$ go get github.com/harwoeck/apperr

Usage

Create

To create errors use one of the provided functions from apperr, like apperr.Unauthenticated(msg)

err := apperr.Unauthenticated("provided password is invalid",
    apperr.Localize("INVALID_PASSWORD"))

apperr can provide localized error messages to users, when a LocalizationProvider is available. In order to add a translation message id to your *AppError you can use one of the provided Option (in the example Localize(messageID) is used)

Render

In order to render an *AppError into a *RenderedError use the static function Render:

rendered, _ := apperr.Render(err, apperr.RenderLocalized(adapter, "en-US"))
Convert

Use the Convert function from your installed converter to translate the *RenderedError from last step to your frameworks native error type:

  • GRPC
    • Install converter go get github.com/harwoeck/apperr/x/grpcerr
    • grpcStatus, err := grpcerr.Convert(*finalized.Error)
      
  • HTTP
    • Install converter go get github.com/harwoeck/apperr/x/httperr
    • httpStatus, httpBody, err := httperr.Convert(*finalized.Error)
      
  • Twirp
    • Install converter go get github.com/harwoeck/apperr/x/twirperr
    • twirpError := twirperr.Convert(*finalized.Error)
      
  • Terminal or Console
    • Install converter go get github.com/harwoeck/apperr/x/terminalerr
    • output := terminalerr.Convert(*finalized.Error)
      fmt.Println(output)
      

Documentation

Overview

Package apperr provides a unified application-error generation interface. Errors constructed with apperr can be localized and extended/modified with other options. When finalized they are rendered into a RenderedError object, which can be converted to native error types for various different frameworks like GRPC, Twirp, Plain-HTTP, etc.

Example:

err := apperr.Unauthenticated("provided password is invalid",
    apperr.Localize("INVALID_PASSWORD"))

Setup:

// configure i18n adapter
i18nAdapter := NewI18nAdapter(config)

// configure language matcher with available languages for i18n
matcher := language.NewMatcher([]language.Tag{language.English, language.German})

In a middleware/interceptor:

// call request handler and get error back
err := handler(r, w)

// check if request failed with apperr, or for unknown reasons (then
// default to Internal
var ae *apperr.AppError
if x, ok := err.(*apperr.AppError); ok {
    ae = x
} else {
    ae = apperr.Internal("internal error")
}

// get best match for user language
t, q, err := language.ParseAcceptLanguage(r.Header.Get("Accept-Language"))
userLang, _, _ := matcher.Match(t...)

// finalize error to something we can return to users
rendered := finalizer.Render(ae, finalizer.WithLocalizationProvider(i18nAdapter))

// convert rendered error to the output format of our protocol
httpStatus, httpBody, _ := httperr.Convert(rendered)

Example Output:

httpStatus = 401 (Unauthorized)
httpBody =
{
    "message": "provided password is invalid",
    "code": "Unauthenticated",
    "localized": {
        "userMessage": "The entered password isn't correct. Please try again",
        "userMessageShort": "Not authenticated",
        "locale": "en-US"
    }
}

The provided converters are:

  1. GRPC (go get github.com/harwoeck/apperr/grpcerr) grpcStatus, err := grpcerr.Convert(*RenderedError)
  2. HTTP (go get github.com/harwoeck/apperr/httperr) httpStatus, httpBody, err := httperr.Convert(*RenderedError)
  3. Twirp (go get github.com/harwoeck/apperr/twirperr) twirpError := twirperr.Convert(*RenderedError)
  4. Terminal (go get github.com/harwoeck/apperr/terminalerr) fmt.Println(terminalerr.Convert(*RenderedError))

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

This section is empty.

Types

type AppError

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

AppError represents a general application error

func Aborted

func Aborted(msg string, opts ...Option) *AppError

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 AlreadyExists

func AlreadyExists(msg string, opts ...Option) *AppError

AlreadyExists means an attempt to create an entity failed because one already exists.

func Canceled

func Canceled(msg string, opts ...Option) *AppError

Canceled indicates the operation was canceled (typically by the caller).

func DataLoss

func DataLoss(msg string, opts ...Option) *AppError

DataLoss indicates unrecoverable data loss or corruption.

func DeadlineExceeded

func DeadlineExceeded(msg string, opts ...Option) *AppError

DeadlineExceeded means operation expired before completion. For operations that change the state of the system, this error may be returned even if the operation has completed successfully. For example, a successful response from a server could have been delayed long enough for the deadline to expire.

func FailedPrecondition

func FailedPrecondition(msg string, opts ...Option) *AppError

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, a 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 Internal

func Internal(msg string, opts ...Option) *AppError

Internal errors. Means some invariants expected by underlying system has been broken. If you see one of these errors, something is very broken.

func InvalidArgument

func InvalidArgument(msg string, opts ...Option) *AppError

InvalidArgument 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 NotFound

func NotFound(msg string, opts ...Option) *AppError

NotFound means some requested entity (e.g., file or directory) was not found.

func OutOfRange

func OutOfRange(msg string, opts ...Option) *AppError

OutOfRange means operation was attempted past the valid range. E.g., seeking or reading past end of file.

Unlike InvalidArgument, this error indicates a problem that may be fixed if the system state changes. For example, a 32-bit file system will generate InvalidArgument if asked to read at an offset that is not in the range [0,2^32-1], but it will generate OutOfRange if asked to read from an offset past the current file size.

There is a fair bit of overlap between FailedPrecondition and OutOfRange. We recommend using OutOfRange (the more specific error) when it applies so that callers who are iterating through a space can easily look for an OutOfRange error to detect when they are done.

func PermissionDenied

func PermissionDenied(msg string, opts ...Option) *AppError

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).

func ResourceExhausted

func ResourceExhausted(msg string, opts ...Option) *AppError

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

func Unauthenticated

func Unauthenticated(msg string, opts ...Option) *AppError

Unauthenticated indicates the request does not have valid authentication credentials for the operation.

func Unavailable

func Unavailable(msg string, opts ...Option) *AppError

Unavailable indicates the service is currently unavailable. This is a most likely a transient condition and may be corrected by retrying with a backoff. Note that it is not always safe to retry non-idempotent operations.

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

func Unimplemented

func Unimplemented(msg string, opts ...Option) *AppError

Unimplemented indicates operation is not implemented or not supported/enabled in this service.

func Unknown

func Unknown(msg string, opts ...Option) *AppError

Unknown error. An example of where this error may be returned is if a Status value received from another address space belongs to an error-space that is not known in this address space. Also, errors raised by APIs that do not return enough error information may be converted to this error.

func (*AppError) AppendOptions

func (a *AppError) AppendOptions(opts ...Option)

AppendOptions adds further Option to AppError instance

func (*AppError) Code

func (a *AppError) Code() code.Code

Code returns the code

func (*AppError) Error

func (a *AppError) Error() string

Error implements Go's error interface

func (*AppError) Message

func (a *AppError) Message() string

Message returns the message

func (*AppError) Opts

func (a *AppError) Opts() []Option

Opts returns the accumulated options

type Option

type Option func(*finalizer.Error) error

Option provide functional modifiers for finalizer.Error instances.

func ErrorInfo

func ErrorInfo(reason string, domain string, metadata map[string]string) Option

ErrorInfo should describe the cause of the error with more structured details.

The `reason` should be a constant value that identifies the proximate cause of the errors.

The `domain` refers to the logical grouping to which the reason belongs. The value is typically the registered service name of the service generating the error, like "api.store.example.com". The domain should be a globally unique value and should be constant within the service infrastructure.

`metadata` can attach further structured meta information to the error. The key must not exceed 64 characters in length.

func FieldViolation

func FieldViolation(field string, description string) Option

FieldViolation describes a single bad request field in a client request.

The `field` must focus on the syntactic aspects of the request, e.g. a path leading to the field in the response body, like "book.author_id". The path in the field value must be a sequence of dot-separated identifiers.

The `description` should explain why the request element is bad. The value must be safe to return to the end user and should be printable for GUI applications.

func FieldViolationLocalize

func FieldViolationLocalize(field string, descriptionID string) Option

FieldViolationLocalize is like FieldViolation, but localizes the description using the descriptionID in the same way as Localize.

func FieldViolationLocalizeAny

func FieldViolationLocalizeAny(field string, descriptionAny interface{}) Option

FieldViolationLocalizeAny is like FieldViolation, but localizes the description using the descriptionAny in the same way as LocalizeAny.

func HelpLink(url string, description string) Option

HelpLink provides URLs to documentation or for performing an out-of-band action. For example, if a quota check failed with an error indicating the calling project hasn't enabled the accessed service, this can contain a URL pointing directly to the right place in a dashboard to flip the bit.

The `description` should explain what the link offers and is only intended for client developers and should not be localized.

func Localize

func Localize(messageID string) Option

Localize sets a unique message ID that can later be resolved using a LocalizationProvider. The message must be safe to return to the end user and should be printable for GUI applications.

func LocalizeAny

func LocalizeAny(any interface{}) Option

LocalizeAny is like Localize but provides an untyped object for the LocalizationProvider instead of a string message ID.

func PreconditionViolation

func PreconditionViolation(violationType string, subject string, description string) Option

PreconditionViolation describes a single precondition violation. For example, conflicting object revisions during an update call.

The `violationType` should be a service-specific enum type to define the supported precondition violation subjects. For example, "UNKNOWN_AUTHOR".

The `subject` references the object, relative to the type, that failed, like "book.author".

The `description` should explain how the precondition failed. Developers can use this description to understand how to fix the failure.

func QuotaViolation

func QuotaViolation(subject string, description string) Option

QuotaViolation describes a single quota violation. For example, a daily quota or a custom quota that was exceeded.

The subject must reference the object on which the quota check failed. For example, "ip:<ip address of client>" or "project:<project id>".

The description should contain more information about how the quota check failed. Clients can use this description to find more about the quota configuration in the service's public documentation. For example: "Service disabled" or "Daily Limit for read operations exceeded".

func RequestInfo

func RequestInfo(requestID string, requestDuration *time.Duration, servingData string, approximatedLatency *time.Duration) Option

RequestInfo adds metadata about the request that clients can attach when filling a bug or providing other forms of feedback.

The `requestID` should be an opaque non-confidential string. For example, it can be used to identify requests in the service's logs or across the infrastructure.

`requestDuration` is the duration between the start and the end of this request. It can be useful to identify inconsistencies between latency and computation time on the server. It should not be specified for endpoints that perform cryptographic operations to prevent timing side channel attacks.

`servingData` can be any data that was used to serve this request. For example, an encrypted stack trace that can be sent back to the service provider for debugging.

`approximatedLatency` should be the approximated client-to-server latency.

func ResourceInfo

func ResourceInfo(resourceType string, name string, owner string, description string) Option

ResourceInfo adds information about the resource being accessed.

The `resourceType` should be a unique name of the resource, e.g. "example.com/store.v1.Book".

The `name` must be the unique identifier of the resource being accessed.

`owner` can be populated if it doesn't impose any security and privacy risks, e.g. the ownership is public knowledge anyway.

`description` should explain what error is encountered when accessing this resource. For example, updating a project may require the "writer" permission for the project. The description is only intended for client developers and should not be localized.

func RetryInfo

func RetryInfo(delay time.Duration) Option

RetryInfo sets a minimum delay when the clients can retry a failed request. In general clients should always use this in combination with exponential backoff, e.g. if the first request after the `delay` timeout fails, clients should gradually increase the delay between retries, until either a maximum number of retries have been reached or a maximum retry delay cap has been reached.

Directories

Path Synopsis
adapter
i18n Module
apperr module
example module
grpcerr module
httperr module
terminalerr module
twirperr module
utils
dto
x
grpcerr Module
httperr Module
terminalerr Module
twirperr Module

Jump to

Keyboard shortcuts

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