errors

package
v0.3.1 Latest Latest
Warning

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

Go to latest
Published: Mar 14, 2024 License: Apache-2.0 Imports: 9 Imported by: 0

README

Errors package

This package provides you with basic structures and helper functions for managing errors in web services/applications. The most common errors are handled and it is easy to use them in new or ongoing projects. The main difference with the previous version of the custom errors package is type safety and embedding errors in customized application errors.

Conflict error

conflict error represents the state when the app tries to insert or create a resource that already exists. It can be used as a zero value, initialized with struct fields or using a helper function like Conflict.

Let's see first with zero value:

return &errors.ConflictError{}

the result will look like this:

resource already exist

another example is with the Item field value:

return &errors.ConflictError{
    Item: 123,
}

and error will be: when the Item is non nil value then we can use this value for additional processing. The Msg field takes precedence over the Item field and that value will be returned as error text. then an error will be: article already exists.

There are also helper functions that will make error handling more friendly. from the above examples you can check the new format specifier ${} which helps you to fill the Item field in the ConflictError struct. When an Item is nonnull you can read the value using cerr, ok := errors.AsConflict(err) then cerr contains Item field value cerr.Item.(int)

Extending ConflictError

using struct embedding in golang we can have some sort of inheritance. In the following example, ConflictError will be embedded into MergeConflictError.

type MergeConflictError struct {
	ConflictError
	Base  string   `json:"base"`
	Head  string   `json:"head"`
	Files []string `json:"files"`
}

func (e *mergeConflictError) Error() string {
	return fmt.Sprintf("merge failed for base '%s' and head '%s'", e.Base, e.Head)
}
Basic Example
func insertArticle(article Article) error {
    return errors.Conflict("article ${%d} already exist", article.ID)
}

func serviceInsertArticle(article Article) error {
    err := insertArticle(article)
    if cerr, ok := errors.AsConflict(err); ok {
        log.Println(cerr.Item.(int))
    }
}

func handler(w http.ResponseWriter, r *http.Request) {
    err := insertArticle(artice)
    if err != nil {
        errors.JSONResponse(w, err)
        return
    }
}

NotFound error

not found error shows an error message when the resource is not found. It can be used as a zero value, initialized with struct fields or using a helper function like NotFound.

Let's see first with zero value:

return &errors.NotFoundError{}

the result will look like this:

resource not found

another example is with the Item field value:

return &errors.NotFoundError{
    Item: 123,
}

and error will be: when the Item is non nil value then we can use this value for additional processing.

The Msg field takes precedence over the Item field and that value will be returned as error text. then an error will be: article not found.

There are also helper functions that will make error handling more friendly.

errors.NotFound("article 123 not found")
errors.NotFound("article %d not found", 123)
errors.NotFound("article ${123} not found")
errors.NotFound("article ${%d} not found", 123)

from the above examples you can check the new format specifier ${} which helps you to fill the Item field in the NotFoundError struct. When an Item is nonnull you can read the value using cerr, ok := errors.AsConflict(err)then cerr containsItemfield valuecerr.Item.(int)`

Basic Example
func getArticle(id int) error {
    return errors.NotFound("article ${%d} not found", id)
}

func getArticleService(id int) (Article, error) {
    a, err := getArticle(id)
    if nferr, ok := errors.AsNotFound(err); ok {
        log.Println(nferr.Item.(int))
    }
}

func handler(w http.ResponseWriter, r *http.Request) {
    err := getArticle(artice)
    if err != nil {
        errors.JSONResponse(w, err)
        return
    }
}

Other types needs to be documented, you can look source code

Documentation

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

func As

func As(err error, target any) bool

As finds the first error in err's tree that matches target, and if one is found, sets target to that error value and returns true. Otherwise, it returns false.

func HttpStatus

func HttpStatus(err error) int

func Is

func Is(err error, target error) bool

Is reports whether any error in err's tree matches target.

func IsConflict

func IsConflict(err error) bool

IsConflict checks if err is conflict error.

func IsInternal

func IsInternal(err error) bool

IsInternal checks if err is internal error.

func IsNotFound

func IsNotFound(err error) bool

IsNotFound checks if err is not found error.

func IsNotImplemented

func IsNotImplemented(err error) bool

IsNotImplemented checks if err is not implemented error.

func IsPreconditionFailed

func IsPreconditionFailed(err error) bool

IsInternal checks if err is internal error.

func IsUnauthenticated

func IsUnauthenticated(err error) bool

func IsUnauthorized

func IsUnauthorized(err error) bool

func IsValidation added in v0.3.1

func IsValidation(err error) bool

IsValidation checks if err is invalid argument error.

func JSONResponse added in v0.3.1

func JSONResponse(w http.ResponseWriter, err error, options ...JSONResponseOption) error

func Join

func Join(errs ...error) error

Join returns an error that wraps the given errors.

func New

func New(text string) error

New returns an error that formats as the given text. Each call to New returns a distinct error value even if the text is identical.

func TraceID added in v0.3.1

func TraceID(id string, t error) error

func Unwrap

func Unwrap(err error) error

Unwrap returns the result of calling the Unwrap method on err, if err's type contains an Unwrap method returning error. Otherwise, Unwrap returns nil.

Types

type Base added in v0.3.1

type Base struct {
	// Msg contains user friendly error.
	Msg       string    `json:"message"`
	Status    int       `json:"status,omitempty"`
	TraceID   string    `json:"trace_id,omitempty"`
	Timestamp time.Time `json:"timestamp,omitempty"`
}

func NewBase added in v0.3.1

func NewBase(status int, format string, args ...any) Base

func (*Base) GetBase added in v0.3.1

func (b *Base) GetBase() *Base

func (*Base) SetTraceID added in v0.3.1

func (b *Base) SetTraceID(id string)

type ConflictError added in v0.3.1

type ConflictError struct {
	Base
	// Item is a conflicting resource.
	Item   any               `json:"item,omitempty"`
	Errors MarshalableErrors `json:"errors"`
}

ConflictError holds fields for conflict error.

func AsConflict added in v0.3.1

func AsConflict(err error) (cerr *ConflictError, b bool)

AsConflict return err as ConflictError or nil if it is not successfull.

func Conflict

func Conflict(format string, args ...any) *ConflictError

Conflict is a helper function to return an ConflictError. In format argument Item can be specified with ${} specifier for example:

  • errors.Conflict("article ${123} already exist")
  • errors.Conflict("article ${%d} already exist", 123)
  • errors.Conflict("group %s and article ${%d} already exist", 1, 123)

the value of Item in ConflictError will be set to 123.

func (*ConflictError) AddError added in v0.3.1

func (e *ConflictError) AddError(err error) *ConflictError

func (*ConflictError) Error added in v0.3.1

func (e *ConflictError) Error() string

Error interface method.

func (*ConflictError) HttpStatus added in v0.3.1

func (e *ConflictError) HttpStatus() int

HttpStatus returns http status for ConflictError.

func (*ConflictError) Is added in v0.3.1

func (e *ConflictError) Is(t error) bool

Is checks if err is ConflictError.

type InternalError added in v0.3.1

type InternalError struct {
	Base
	Err        error           `json:"-"`
	Stacktrace json.RawMessage `json:"-"`
}

func AsInternal added in v0.3.1

func AsInternal(err error) (ierr *InternalError, b bool)

func Internal

func Internal(err error, format string, args ...any) *InternalError

Internal is a helper function to return an internal Error.

func (*InternalError) Error added in v0.3.1

func (e *InternalError) Error() string

func (*InternalError) HttpStatus added in v0.3.1

func (e *InternalError) HttpStatus() int

type JSONResponseFunc added in v0.3.1

type JSONResponseFunc func(*Base)

func ProcessStatus added in v0.3.1

func ProcessStatus(fn func(status int) error) JSONResponseFunc

func WithTraceID added in v0.3.1

func WithTraceID(traceID string) JSONResponseFunc

func (JSONResponseFunc) Apply added in v0.3.1

func (f JSONResponseFunc) Apply(b *Base)

type JSONResponseOption added in v0.3.1

type JSONResponseOption interface {
	Apply(*Base)
}

type MarshalableErrors added in v0.3.1

type MarshalableErrors []error

func (MarshalableErrors) MarshalJSON added in v0.3.1

func (me MarshalableErrors) MarshalJSON() ([]byte, error)

type NotFoundError added in v0.3.1

type NotFoundError struct {
	Base
	Item any `json:"item,omitempty"`
}

func AsNotFound added in v0.3.1

func AsNotFound(err error) (nerr *NotFoundError, b bool)

AsNotFound return err as NotFoundError or nil if it is not successfull.

func NotFound

func NotFound(format string, args ...any) *NotFoundError

NotFound is a helper function to return an NotFoundError. In format argument Item can be specified with ${} specifier for example:

  • errors.NotFound("article ${123} already exist")
  • errors.NotFound("article ${%d} already exist", 123)
  • errors.NotFound("group %s and article ${%d} already exist", 1, 123)

the value of Item in NotFoundError will be set to 123.

func (*NotFoundError) Error added in v0.3.1

func (e *NotFoundError) Error() string

Error interface method.

func (*NotFoundError) HttpStatus added in v0.3.1

func (e *NotFoundError) HttpStatus() int

Is returns http status for NotFoundError

func (*NotFoundError) Is added in v0.3.1

func (e *NotFoundError) Is(err error) bool

type NotImplementedError added in v0.3.1

type NotImplementedError struct {
	Base
}

func NotImplemented

func NotImplemented(format string, args ...any) *NotImplementedError

InvalidArgument is a helper function to return an invalid argument Error.

func (*NotImplementedError) Error added in v0.3.1

func (e *NotImplementedError) Error() string

func (*NotImplementedError) HttpStatus added in v0.3.1

func (e *NotImplementedError) HttpStatus() int

type PreconditionFailedError added in v0.3.1

type PreconditionFailedError struct {
	Base
	Err error
}

func PreconditionFailed

func PreconditionFailed(format string, args ...interface{}) *PreconditionFailedError

Internal is a helper function to return an internal Error.

func (*PreconditionFailedError) Error added in v0.3.1

func (e *PreconditionFailedError) Error() string

func (*PreconditionFailedError) HttpStatus added in v0.3.1

func (e *PreconditionFailedError) HttpStatus() int

func (*PreconditionFailedError) SetErr added in v0.3.1

type UnauthenticatedError added in v0.3.1

type UnauthenticatedError struct {
	Base
}

func Unauthenticated

func Unauthenticated(format string, args ...any) *UnauthenticatedError

func (*UnauthenticatedError) Error added in v0.3.1

func (e *UnauthenticatedError) Error() string

func (*UnauthenticatedError) HttpStatus added in v0.3.1

func (e *UnauthenticatedError) HttpStatus() int

type UnauthorizedError added in v0.3.1

type UnauthorizedError struct {
	Base
}

func Unauthorized

func Unauthorized(format string, args ...any) *UnauthorizedError

func (*UnauthorizedError) Error added in v0.3.1

func (e *UnauthorizedError) Error() string

func (*UnauthorizedError) HttpStatus added in v0.3.1

func (e *UnauthorizedError) HttpStatus() int

type ValidationError added in v0.3.1

type ValidationError struct {
	Base
	Errors MarshalableErrors `json:"errors,omitempty"`
}

func AsValidation added in v0.3.1

func AsValidation(err error) (verr *ValidationError, b bool)

func Validation added in v0.3.1

func Validation(format string, args ...any) *ValidationError

Validation is a helper function to return an invalid argument Error.

func (*ValidationError) AddError added in v0.3.1

func (e *ValidationError) AddError(err error) *ValidationError

func (*ValidationError) Error added in v0.3.1

func (e *ValidationError) Error() string

func (*ValidationError) HttpStatus added in v0.3.1

func (e *ValidationError) HttpStatus() int

func (*ValidationError) Is added in v0.3.1

func (e *ValidationError) Is(err error) bool

Jump to

Keyboard shortcuts

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