exterrors

package module
v0.0.0-...-0e2bc54 Latest Latest
Warning

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

Go to latest
Published: May 12, 2020 License: MIT Imports: 4 Imported by: 16

README

ext-errors

Package exterrors provides extended error handling primitives to add a bit more info to errors returning from the function.

go get github.com/eugeneradionov/ext-errors

Motivation

In every API that handles HTTP requests, we need to work with error handling. We'd like to add extra information about the response status and can't figure it out with the standard errors package. With exterrors package, you know the status of your request in any place of the application.

Usage

Use ExtError interface instead of standard error

func GetUserByID(id string) (User, exterrors.ExtError) {
    user, err := db.GetUserByID(id)
    if err != nil {
        return User{}, exterrors.NewInternalServerError(err)
    }
    
    return user, nil
}

func GetUserHandler(w http.ResponseWriter, r *http.Request) {
    w.Header().Set("Content-Type", "application/json;charset=utf-8")    
    
    user, extErr := GetUserByID("user_id_1")
    if extErr != nil {
        SendExtError(w, extErr)
        return
    }
}

func SendExtError(w http.ResponseWriter, extErr exterrors.ExtError) {
    var statusCode = extErr.HTTPCode()

    w.Header().Set("Content-Type", "application/json;charset=utf-8")
    errResp, err := json.Marshal(extErr)
    if err != nil {
        statusCode = http.StatusInternalServerError
    }
    
    w.WriteHeader(statusCode)
    w.Write(errResp)
}

Use ExtErrors for handling multiple errors

func GetUsersHandler(w http.ResponseWriter, r *http.Request) {
    w.Header().Set("Content-Type", "application/json;charset=utf-8")    
    
    extErrs := exterrors.NewExtErrors()

    user1, extErr := GetUserByID("user_id_1")
    if extErr != nil {
        extErrs.Add(extErr)
    }

    user2, extErr := GetUserByID("user_id_2")
    if extErr != nil {
        extErrs.Add(extErr)
    }

    SendExtErrors(w, extErrs)
}

func SendExtErrors(w http.ResponseWriter, extErrs exterrors.ExtErrors) {
    var statusCode = extErrs.HTTPCode() // Set the status code according to error type

    w.Header().Set("Content-Type", "application/json;charset=utf-8")
    errResp, err := json.Marshal(extErrs)
    if err != nil {
        statusCode = http.StatusInternalServerError
    }
    
    w.WriteHeader(statusCode)
    w.Write(errResp)
}

Caveats

As ExtError requires implementation of standard error interface to be compatible with it, be careful, when trying to assign function result ExtError to the variable with standard error type. This could cause unpredictable behavior.

Documentation

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

This section is empty.

Types

type Error

type Error struct {

	// Code contains info about HTTP code
	// that could be sent in the status of the HTTP response.
	Code int `json:"-"`

	// Message contains error message if any.
	Message string `json:"message,omitempty"`

	// Description contains detailed error information if any.
	Description string `json:"description,omitempty"`

	// Field describes in which field an error has occurred if any.
	// For example JSON field in the HTTP request body.
	// Typically is used for pointing an invalid field during validation.
	Field string `json:"field,omitempty"`
}

Error contains extended error information.

func (Error) ErrDescription

func (e Error) ErrDescription() string

func (Error) ErrField

func (e Error) ErrField() string

func (Error) ErrMessage

func (e Error) ErrMessage() string

func (Error) Error

func (e Error) Error() string

Error unifying Error with Go's error interface.

func (Error) HTTPCode

func (e Error) HTTPCode() int

func (Error) MarshalJSON

func (e Error) MarshalJSON() ([]byte, error)

type Errors

type Errors struct {
	Errs []ExtError `json:"errors"`
}

Errors represents multiple errors occurred. Useful for validation errors when required to show all errors at once.

func (*Errors) Add

func (errs *Errors) Add(err ...ExtError)

func (Errors) Error

func (errs Errors) Error() string

func (Errors) Errors

func (errs Errors) Errors() []ExtError

func (Errors) Len

func (errs Errors) Len() int

func (Errors) MarshalJSON

func (errs Errors) MarshalJSON() ([]byte, error)

type ExtError

type ExtError interface {
	error
	json.Marshaler

	// HTTPCode contains info about HTTP code
	// that could be sent in the status of the HTTP response.
	HTTPCode() int

	// ErrMessage contains error message if any.
	ErrMessage() string

	// ErrDescription returns error detailed info.
	ErrDescription() string

	// ErrField describes in which field an error has occurred if any.
	// For example JSON field in the HTTP request body.
	// Typically is used for pointing an invalid field during validation.
	ErrField() string
}

ExtError describes extended error. Can be used in the same way as basic error.

func NewBadRequestError

func NewBadRequestError(err error) ExtError

func NewError

func NewError(err error, code int, message, field string) ExtError

NewError returns new ExtError with filled Message, Description and Field.

func NewForbiddenError

func NewForbiddenError(err error) ExtError

func NewInternalServerErrorError

func NewInternalServerErrorError(err error) ExtError

func NewNotFoundError

func NewNotFoundError(err error, field string) ExtError

func NewUnauthorizedError

func NewUnauthorizedError(err error) ExtError

func NewUnprocessableEntityError

func NewUnprocessableEntityError(err error, field string) ExtError

type ExtErrors

type ExtErrors interface {
	error
	json.Marshaler

	// Add adds new ExtError to the slice.
	Add(...ExtError)

	// Errors returns the slice of ExtError for future processing.
	Errors() []ExtError

	// Len returns current number of added errors.
	Len() int
}

func NewExtErrors

func NewExtErrors() ExtErrors

NewExtErrors returns usage ready instance of ExtErrors.

func NewExtErrorsWithCap

func NewExtErrorsWithCap(capacity int) ExtErrors

NewExtErrorsWithCap returns instance of ExtErrors with specified capacity of underlying slice.

Jump to

Keyboard shortcuts

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