Categorygithub.com/gildas/go-errors
modulepackage
0.4.0
Repository: https://github.com/gildas/go-errors.git
Documentation: pkg.go.dev

# README

go-errors

GoVersion GoDoc License Report

master Test codecov

dev Test codecov

This is a library for handling errors in Go language.

Usage

This package combines Go standard errors package and github.com/pkg/errors.

All funcs from both packages are available.

On top of them, I added some sentinels for common errors I need all the time.

All sentinels are from the same type which contains various information. Whenever a sentinel is used, a StackTrace is also generated.

Here is how to use the errors:

func findme(stuff map[string]string, key string) (string, error) {
    if value, found := stuff[key]; found {
        return value, nil
    }
    return "", errors.NotFound.With("key", key)
}

func main() {
    var allstuff[string]string
    //...
    value, err := findme("key1")
    if errors.Is(err, errors.NotFound) {
        fmt.Fprintf(os.Stderr, "Error: %+v", err)
        // This should print the error its wrapped content and a StackTrace.
    }
}

If you plan to do something with the content of the error, you would try that:

func main() {
    var allstuff[string]string
    //...
    value, err := findme("key1")
    if errors.Is(err, errors.NotFound) {
        var details *errors.Error
        if errors.As(err, &details) {
            fmt.Fprintf(os.Stderr, "Could not find %s", details.What)
        }
    }
}

Note: You should not use var details errors.Error, use the pointer version var details *errors.Error instead.

When several errors.Error are chained up, this can be used to extract the ones you want:

func main() {
    var allstuff[string]string
    //...
    value, err := findme("key1")
    if errors.Is(err, errors.NotFound) {
        details := errors.NotFound.Clone()
        if errors.As(err, &details) {
            fmt.Fprintf(os.Stderr, "Could not find %s", details.What)
        }
    }
}

To return an HTTP Status as an error, you could do this:

func doit() error {
    req, err := http.NewRequest(http.MethodGet, "http://www.acme.org")
    if err != nil {
        return errors.WithStack(err)
    }
    httpclient := http.DefaultClient()
    res, err := httpclient.Do(req)
    if err != nil {
        return errors.WithStack(err)
    }
    if res.StatusCode >= 400 {
        return errors.FromHTTPStatusCode(res.StatusCode)
    }
    return nil
}

func main() {
    err := doit()
    if (errors.Is(err, errors.HTTPBadRequest)) {
        // do something
    }
    // do something else
}

You can chain multiple errors together (See Example):

func doit() error {
    // ... some processing
    var urlError *url.Error // errors from the net/url package

    return errors.WrapErrors(err, errors.NotFound.With("key", "key1"), urlError)
}

You can also use a errors.MultiError to collect multiple errors together (See Example):

me := errors.MultiError{}
me.Append(errors.NotFound.With("key", "key1"))
me.Append(errors.NotFound.With("key", "key2"))
fmt.Println(me.AsError())

Finally, errors.Error supports JSON serialization:

err := errors.InvalidType.With("bogus")
payload, jerr := json.Marshal(err)
// ...

# Functions

As finds the first error in err's chain that matches target, and if so, sets target to that error value and returns true.
Errorf formats according to a format specifier and returns the string as a value that satisfies error.
FromHTTPStatusCode creates a new error of the sentinel that matches the given HTTP status code.
Is reports whether any error in err's chain matches target.
Join returns an error wrapping given errors If the first or the last error in the chain is nil, Join returns nil.
New returns a new error with the supplied message.
NewSentinel creates a new sentinel.
Unwrap returns the result of calling the Unwrap method on err, if err's type contains an Unwrap method returning error.
WithMessage annotates err with a new message.
WithMessagef annotates err with the format specifier.
WithoutStack removes the stack trace from the current error If err is nil, WithStack returns nil.
WithStack annotates err with a stack trace at the point WithStack was called.
Wrap returns an error annotating err with a stack trace at the point Wrap is called, and the supplied message.
WrapErrors returns an error wrapping given errors If the first or the last error in the chain is nil, WrapErrors returns nil.
Wrapf returns an error annotating err with a stack trace at the point Wrapf is called, and the format specifier.

# Variables

ArgumentExpected is used when an argument is expected and another was set.
ArgumentInvalid is used when an argument has an unexpected value.
ArgumentMissing is used when an argument is missing.
CreationFailed is used when something was not created properly.
DuplicateFound is used when something is found but it should not have been.
Empty is used when something is empty whereas it should not.
EnvironmentInvalid is used when an argument has an unexpected value.
EnvironmentMissing is used when an argument is missing.
HTTPBadGateway is used when an http.Client request fails.
HTTPBadRequest is used when an http.Client request fails.
HTTPForbidden is used when an http.Client request fails.
HTTPInternalServerError is used when an http.Client request fails.
HTTPMethodNotAllowed is used when an http.Client request fails.
HTTPNotFound is used when an http.Client request fails.
HTTPNotImplemented is used when an http.Client request fails.
HTTPServiceUnavailable is used when an http.Client request fails.
HTTPStatusConflict reports HTTP Error StatusConflict.
HTTPStatusExpectationFailed reports HTTP Error StatusExpectationFailed.
HTTPStatusFailedDependency reports HTTP Error StatusFailedDependency.
HTTPStatusGatewayTimeout reports HTTP Error StatusGatewayTimeout.
HTTPStatusGone reports HTTP Error StatusGone.
HTTPStatusHTTPVersionNotSupported reports HTTP Error StatusHTTPVersionNotSupported.
HTTPStatusInsufficientStorage reports HTTP Error StatusInsufficientStorage.
HTTPStatusLengthRequired reports HTTP Error StatusLengthRequired.
HTTPStatusLocked reports HTTP Error StatusLocked.
HTTPStatusLoopDetected reports HTTP Error StatusLoopDetected.
HTTPStatusMisdirectedRequest reports HTTP Error StatusMisdirectedRequest.
HTTPStatusNetworkAuthenticationRequired reports HTTP Error StatusNetworkAuthenticationRequired.
HTTPStatusNotAcceptable reports HTTP Error StatusNotAcceptable.
HTTPStatusNotExtended reports HTTP Error StatusNotExtended.
HTTPStatusPaymentRequired reports HTTP Error StatusPaymentRequired.
HTTPStatusPreconditionFailed reports HTTP Error StatusPreconditionFailed.
HTTPStatusPreconditionRequired reports HTTP Error StatusPreconditionRequired.
HTTPStatusProxyAuthRequired reports HTTP Error StatusProxyAuthRequired.
HTTPStatusRequestedRangeNotSatisfiable reports HTTP Error StatusRequestedRangeNotSatisfiable.
HTTPStatusRequestEntityTooLarge reports HTTP Error StatusRequestEntityTooLarge.
HTTPStatusRequestHeaderFieldsTooLarge reports HTTP Error StatusRequestHeaderFieldsTooLarge.
HTTPStatusRequestTimeout reports HTTP Error StatusRequestTimeout.
HTTPStatusRequestURITooLong reports HTTP Error StatusRequestURITooLong.
HTTPStatusTeapot reports HTTP Error StatusTeapot.
HTTPStatusTooEarly reports HTTP Error StatusTooEarly.
HTTPStatusTooManyRequests reports HTTP Error StatusTooManyRequests.
HTTPStatusUnavailableForLegalReasons reports HTTP Error StatusUnavailableForLegalReasons.
HTTPStatusUnprocessableEntity reports HTTP Error StatusUnprocessableEntity.
HTTPStatusUnsupportedMediaType reports HTTP Error StatusUnsupportedMediaType.
HTTPStatusUpgradeRequired reports HTTP Error StatusUpgradeRequired.
HTTPStatusUseProxy reports HTTP Error StatusUseProxy.
HTTPStatusVariantAlsoNegotiates reports HTTP Error StatusVariantAlsoNegotiates.
HTTPUnauthorized is used when an http.Client request fails.
IndexOutOfBounds is used when an index is out of bounds.
Invalid is used when something is not valid.
InvalidType is used when a type is not valid.
InvalidURL is used when a URL is not valid.
JSONMarshalError is used when data failed to be marshaled into JSON.
JSONPropertyMissing is used when JSON data is missing a property.
JSONUnmarshalError is used when JSON data is missing a property.
Missing is used when something is missing.
NotConnected is used when some socket, client is not connected to its server.
NotFound is used when something is not found.
NotImplemented is used when some code/method/func is not written yet.
NotInitialized is used when something is not yet initialized.
RuntimeError is used when the code failed executing something.
Timeout is used when something timed out.
TooManyErrors is used when something is found too many times.
Unauthorized is used when some credentials failed some authentication process.
UnknownError is used when the code does not know which error it is facing...
Unsupported is used when something is unsupported by the code.
VERSION is the version of this application.

# Structs

Error describes an augmented implementation of Go's error interface.
MultiError is used to collect errors, like during a loop.

# Type aliases

No description provided by the author
No description provided by the author