porterr

package module
v1.11.2 Latest Latest
Warning

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

Go to latest
Published: Nov 5, 2022 License: BSD-2-Clause Imports: 11 Imported by: 21

README

PORTABLE ERROR

  • Easy to say that your app has an error.
  • Easy to say to your client that app has an error
  • Easy to define any error in your logic
  • Classic error representation

How to use

Simple system error

e := porterr.New(PortErrorSystem, message)

Simple system error with http response code

e := porterr.New(PortErrorSystem, message).HTTP(http.StatusInternalServerError)

Error with details

e := porterr.New(PortErrorSystem, message)
e = e.PushDetail("DETAIL_CODE", "item", "New detail")
e = e.PushDetail("COMMAND_CODE", "command", "Is required")
e = e.PushDetail("COMMAND_CODE", "command", "Some other message")

Easy http validation error

e := porterr.HttpValidationError()

Validation http error with custom code and message

e := porterr.HttpValidationError("CUSTOM_CODE", "your form is invalid")

How to use with validation rules

Form validation use combination of validation rules. Possible rules as parts of 'valid' tag:

  • required. Filed is required
  • exp. Regular expression
  • range. Range if values
  • enum. Predefined enum
  • min. Minimum value or length
  • max. Maximum value or length
  • digit. Only digits in value. Can specify length

Example: valid:"required;exp~[0-5]+;range~1:50;enum~[5,10,15,20,25];digit~4,10;min~3;max~10"

type ComplexStruct struct {
	Cool bool
}
type AliasOnTypeString string
type Nested struct {
	Foo int32 `json:"foo"`
	Bar *bool `json:"bar" valid:"required"`
}
type TestValidationStruct struct {
	Name      string            `json:"name" valid:"required;exp~[a-z]+"`
	Number    int               `json:"number" valid:"exp~[0-5]+;range~1:50;enum~[5,10,15,20,25]"`
	IsTrue    *bool             `json:"isTrue"`
	Complex   *ComplexStruct    `json:"complex" valid:"required"`
	Sl        []int64           `json:"sl"`
	SuperName AliasOnTypeString `json:"superName" valid:"required"`
	Nested    Nested            `json:"nested"`
}
v := TestValidationStruct{Complex: &ComplexStruct{}}
e := porterr.ValidateStruct(&v)
if e != nil {
   panic(e)
}
If you find this project useful or want to support the author, you can send tokens to any of these wallets
  • Bitcoin: bc1qgx5c3n7q26qv0tngculjz0g78u6mzavy2vg3tf
  • Ethereum: 0x62812cb089E0df31347ca32A1610019537bbFe0D
  • Dogecoin: DET7fbNzZftp4sGRrBehfVRoi97RiPKajV

Documentation

Index

Constants

View Source
const (
	// PackControlSymbolTilda ~ symbol
	PackControlSymbolTilda = byte(126)
	// PackControlSymbolVertical | symbol
	PackControlSymbolVertical = byte(124)
)
View Source
const (
	PortErrorSystem        = "PORTABLE_ERROR_SYSTEM"
	PortErrorClient        = "PORTABLE_ERROR_CLIENT"
	PortErrorDatabaseQuery = "PORTABLE_ERROR_DATABASE"
	PortErrorConsole       = "PORTABLE_ERROR_CONSOLE"
	PortErrorLogic         = "PORTABLE_ERROR_LOGIC"
	PortErrorRequest       = "PORTABLE_ERROR_REQUEST"
	PortErrorResponse      = "PORTABLE_ERROR_RESPONSE"
	PortErrorConflict      = "PORTABLE_ERROR_CONFLICT"
	PortErrorTransaction   = "PORTABLE_ERROR_TRANSACTION"
	PortErrorConnection    = "PORTABLE_ERROR_CONNECTION"
	PortErrorUpdate        = "PORTABLE_ERROR_UPDATE"
	PortErrorCreate        = "PORTABLE_ERROR_CREATE"
	PortErrorDelete        = "PORTABLE_ERROR_DELETE"
	PortErrorLoad          = "PORTABLE_ERROR_LOAD"
	PortErrorSearch        = "PORTABLE_ERROR_SEARCH"
	PortErrorParam         = "PORTABLE_ERROR_PARAM"
	PortErrorValidation    = "PORTABLE_ERROR_VALIDATION"
	PortErrorScript        = "PORTABLE_ERROR_SCRIPT"
	PortErrorDescriptor    = "PORTABLE_ERROR_DESCRIPTOR"
	PortErrorNotification  = "PORTABLE_ERROR_NOTIFICATION"
	PortErrorConsumer      = "PORTABLE_ERROR_CONSUMER"
	PortErrorProducer      = "PORTABLE_ERROR_PRODUCER"
	PortErrorCore          = "PORTABLE_ERROR_CORE"
	PortErrorHandler       = "PORTABLE_ERROR_HANDLER"
	PortErrorAccess        = "PORTABLE_ERROR_ACCESS"
	PortErrorPermission    = "PORTABLE_ERROR_PERMISSION"
	PortErrorAuth          = "PORTABLE_ERROR_AUTH"
	PortErrorMigration     = "PORTABLE_ERROR_MIGRATION"
	PortErrorType          = "PORTABLE_ERROR_TYPE"
	PortErrorFunction      = "PORTABLE_ERROR_FUNCTION"
	PortErrorEncoder       = "PORTABLE_ERROR_ENCODER"
	PortErrorDecoder       = "PORTABLE_ERROR_DECODER"
	PortErrorReader        = "PORTABLE_ERROR_READER"
	PortErrorWriter        = "PORTABLE_ERROR_WRITER"
	PortErrorCloser        = "PORTABLE_ERROR_CLOSER"
	PortErrorTemplate      = "PORTABLE_ERROR_TEMPLATE"
	PortErrorCommand       = "PORTABLE_ERROR_COMMAND"
	PortErrorProcess       = "PORTABLE_ERROR_PROCESS"
	PortErrorIO            = "PORTABLE_ERROR_IO"
	PortErrorRender        = "PORTABLE_ERROR_RENDER"
	PortErrorState         = "PORTABLE_ERROR_STATE"
	PortErrorMemory        = "PORTABLE_ERROR_MEMORY"
	PortErrorNetwork       = "PORTABLE_ERROR_NETWORK"
	PortErrorDevice        = "PORTABLE_ERROR_DEVICE"
	PortErrorRecursion     = "PORTABLE_ERROR_RECURSION"
	PortErrorArgument      = "PORTABLE_ERROR_ARGUMENT"
	PortErrorBody          = "PORTABLE_ERROR_BODY"
	PortErrorHeader        = "PORTABLE_ERROR_HEADER"
	PortErrorProtocol      = "PORTABLE_ERROR_PROTOCOL"
	PortErrorSize          = "PORTABLE_ERROR_SIZE"
	PortErrorPriority      = "PORTABLE_ERROR_PRIORITY"
	PortErrorCondition     = "PORTABLE_ERROR_CONDITION"
	PortErrorIteration     = "PORTABLE_ERROR_ITERATION"
	PortErrorParser        = "PORTABLE_ERROR_PARSER"
	PortErrorEnvelop       = "PORTABLE_ERROR_ENVELOP"
	PortErrorEnvironment   = "PORTABLE_ERROR_ENVIRONMENT"
)

Variables

View Source
var (
	// ErrorPackSign Define firse byte for extended error serial protocol
	ErrorPackSign = []byte("xe")
	// PortErrorPackIdentifier check bytes to confirm that is PortError package
	PortErrorPackIdentifier = []byte("pe")
	// PackErrorPrefix Whole preffix for packed error
	PackErrorPrefix = []byte{120, 101, 58, 112, 101, 58}
)

Functions

func IsDigits added in v1.11.1

func IsDigits(val reflect.Value, args ...string) bool

IsDigits check for digits

func IsEnumValid added in v1.10.0

func IsEnumValid(val reflect.Value, args ...string) bool

IsEnumValid In list validation rule

func IsMaxValid added in v1.11.0

func IsMaxValid(val reflect.Value, args ...string) bool

IsMaxValid check max

func IsMinValid added in v1.11.0

func IsMinValid(val reflect.Value, args ...string) bool

IsMinValid check min

func IsRangeValid added in v1.10.0

func IsRangeValid(val reflect.Value, args ...string) bool

IsRangeValid Range list validation rule

func IsRegularValid added in v1.10.0

func IsRegularValid(val reflect.Value, args ...string) bool

IsRegularValid check regular expression

func IsRequiredValid added in v1.10.0

func IsRequiredValid(val reflect.Value, args ...string) bool

IsRequiredValid Required validation rule

func PrepareActualValidationRules added in v1.10.0

func PrepareActualValidationRules(customValidationRules map[string]ValidationCallback)

PrepareActualValidationRules func to append basicValidationRules or replace existing rules customValidationRules If you want to use your own validation rules add the rules in to customValidationRules var

Types

type ErrorData

type ErrorData struct {
	// Code message
	Code interface{}
	// Name of detail
	Name string
	// Error message
	Message string
}

ErrorData Detailed error

func (ErrorData) Serial added in v1.11.2

func (e ErrorData) Serial(buf *bytes.Buffer)

Serial error

type IError

type IError interface {
	// Code Set error code
	Code(code interface{}) IError
	// Error interface std
	Error() string
	// FlushDetails Reset all details
	FlushDetails() IError
	// GetCode Get error code
	GetCode() interface{}
	// GetDetails Get error details
	GetDetails() []IError
	// GetHTTP Get http code
	GetHTTP() int
	// HTTP Set HTTP code
	HTTP(httpCode int) IError
	// IfDetails Return error if error has details else nil
	IfDetails() IError
	// MergeDetails Merge detail to error
	MergeDetails(e ...IError) IError
	// Origin Get portable error
	Origin() *PortError
	// Pack error
	Pack(b *bytes.Buffer)
	// PopDetail Get detail from
	PopDetail() IError
	// PushDetail Add error detail
	PushDetail(code interface{}, name string, message string) IError
}

IError Common Error Interface

func HttpValidationError added in v1.10.3

func HttpValidationError(args ...string) IError

HttpValidationError prepare validation error with 400 http code

func New

func New(code interface{}, message string) IError

New error

func NewF

func NewF(code interface{}, message string, args ...interface{}) IError

NewF error

func NewFWithName

func NewFWithName(code interface{}, name string, message string, args ...interface{}) IError

NewFWithName error with name format

func NewWithName

func NewWithName(code interface{}, name string, message string) IError

NewWithName error with name

func UnPack added in v1.11.0

func UnPack(data []byte) IError

UnPack if bytes contains Port Error

func ValidateStruct added in v1.10.0

func ValidateStruct(v interface{}) IError

ValidateStruct struct fields validation

type PortError

type PortError struct {

	// Error data
	ErrorData
	// contains filtered or unexported fields
}

PortError Portable error

func (*PortError) Code added in v1.7.0

func (e *PortError) Code(code interface{}) IError

Code Set Error Code

func (*PortError) Error

func (e *PortError) Error() string

Interface error method

func (*PortError) FlushDetails

func (e *PortError) FlushDetails() IError

FlushDetails Flush detail

func (*PortError) GetCode added in v1.7.0

func (e *PortError) GetCode() interface{}

GetCode Get Error Code

func (*PortError) GetDetails

func (e *PortError) GetDetails() []IError

GetDetails Interface error get details

func (*PortError) GetHTTP added in v1.3.0

func (e *PortError) GetHTTP() int

GetHTTP Get HTTP Code

func (*PortError) HTTP added in v1.3.0

func (e *PortError) HTTP(httpCode int) IError

HTTP Set HTTP

func (*PortError) IfDetails added in v1.9.0

func (e *PortError) IfDetails() IError

IfDetails Return nil when error does not contain details

func (*PortError) MarshalJSON

func (e *PortError) MarshalJSON() ([]byte, error)

MarshalJSON Std error marshal

func (*PortError) MergeDetails added in v1.8.0

func (e *PortError) MergeDetails(error ...IError) IError

MergeDetails Merge detail from other errors

func (*PortError) Origin added in v1.10.0

func (e *PortError) Origin() *PortError

Origin return origin error

func (*PortError) Pack added in v1.11.0

func (e *PortError) Pack(b *bytes.Buffer)

Pack pack error into []byte

func (*PortError) PopDetail

func (e *PortError) PopDetail() IError

PopDetail Pop detail

func (*PortError) PushDetail

func (e *PortError) PushDetail(code interface{}, name string, message string) IError

PushDetail Interface error push detail

func (*PortError) UnmarshalJSON

func (e *PortError) UnmarshalJSON(data []byte) error

UnmarshalJSON Unmarshal error

type ValidationCallback added in v1.10.0

type ValidationCallback func(val reflect.Value, args ...string) bool

ValidationCallback function that performs validation rule

type ValidationRule added in v1.10.0

type ValidationRule struct {
	// Validator name
	Name string
	// Validator argument
	Args []string
}

ValidationRule validation params

func ParseValidTag added in v1.10.0

func ParseValidTag(validTag string) []ValidationRule

ParseValidTag parse validation tag for rule and arguments Example valid:"exp~[0-5]+;range~1-50;enum~5,10,15,20,25"`

Jump to

Keyboard shortcuts

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