Documentation
¶
Index ¶
- Constants
- func Add(err error, cfg *ErrorConfig) error
- func Create(code string, cfg *ErrorConfig) error
- func GetStackTrace(err error) []runtime.Frame
- func Init(cfg *Config)
- func ParseAcceptLanguage(acceptLang string) ([]language.Tag, []float32, error)
- func ParseAcceptLanguageAsStr(acceptLang string) ([]string, error)
- func Remove(err error)
- func UnwrapMulti(err error) []error
- func UnwrapToRoot(err error) error
- func Wrap(err error) error
- func Wrapf(format string, args ...any) error
- type AppError
- type AppErrors
- type Config
- type ErrorConfig
- type ErrorInfo
- type InfoBuilderConfig
- type InfoBuilderFunc
- type InfoBuilderOption
- func InfoBuilderOptionCustomBuilder(infoBuilderFunc InfoBuilderFunc) InfoBuilderOption
- func InfoBuilderOptionCustomConfig(errorConfig ErrorConfig) InfoBuilderOption
- func InfoBuilderOptionFallbackContent(fallbackToContent bool) InfoBuilderOption
- func InfoBuilderOptionSeparator(errorSeparator string) InfoBuilderOption
- func InfoBuilderOptionTranslateTitle(translateTitle bool) InfoBuilderOption
- func InfoBuilderOptionTranslationFunc(translationFunc TranslationFunc) InfoBuilderOption
- type InfoBuilderResult
- type Language
- type LogLevel
- type MultiError
- type TranslationFunc
- type ValidationError
Constants ¶
const ( LanguageEn = "en" LanguageFr = "fr" LanguageDe = "de" LanguageEs = "es" LanguageIt = "it" LanguagePt = "pt" LanguageRu = "ru" LanguageZh = "zh" LanguageJa = "ja" LanguageKo = "ko" LanguageAr = "ar" LanguageHi = "hi" )
Variables ¶
This section is empty.
Functions ¶
func Add ¶
func Add(err error, cfg *ErrorConfig) error
Add adds a global config mapping for a base error, then returns the error. This function is recommended for adding mapping for app-external errors.
Example:
var ErrRedisKeyNotFound = Add(redis.Nil, &ErrorConfig{
Status: http.StatusNotFound,
Code: "ErrRedisKeyNotFound",
})
func Create ¶
func Create(code string, cfg *ErrorConfig) error
Create creates an error for the code with the mapping config, then returns the newly created error. This function is recommended for adding mapping for app-internal errors. When use this method, you don't need to set custom error code or translation key, they will be the same as the input code.
Example:
var ErrTokenInvalid = Create("ErrTokenInvalid", &ErrorConfig{Status: http.StatusUnauthorized})
var ErrNoPermission = Create("ErrNoPermission", &ErrorConfig{Status: http.StatusForbidden})
func GetStackTrace ¶
GetStackTrace gets stack trace stored in the error if there is
func ParseAcceptLanguage ¶
ParseAcceptLanguage parses header Accept-Language from http request. This func returns a list of `Tag` objects in priority order.
Example:
Accept-Language: * Accept-Language: fr-CH, fr;q=0.9, en;q=0.8, de;q=0.7, *;q=0.5
func ParseAcceptLanguageAsStr ¶
ParseAcceptLanguageAsStr parses header Accept-Language from http request. This func returns a list of `Tag` strings in priority order.
Example:
Accept-Language: "fr-CH, fr;q=0.9, en;q=0.8, *;q=0.5" gives result: ["fr-CH", "fr", "en", "mul"]
func UnwrapMulti ¶
UnwrapMulti unwraps en error to a slice of errors. If the error implements `Unwrap() []error`, the result of func call is returned. If the error implements `Unwrap() error`, the func is called and the result slice has only one element. If no `Unwrap` func is implemented in the error, `nil` is returned.
func UnwrapToRoot ¶
UnwrapToRoot keeps unwrapping until the root error
Types ¶
type AppError ¶
type AppError interface {
error
// Params gets non-translating param map
Params() map[string]any
// TransParams gets translating param map (values of this map will be translated)
TransParams() map[string]string
// Cause gets cause of the error
Cause() error
// Debug gets debug message
Debug() string
// Config returns the custom config if set, otherwise returns the global mapping one
Config() *ErrorConfig
// CustomConfig gets custom config associated with the error
CustomConfig() *ErrorConfig
// CustomBuilder gets custom info builder
CustomBuilder() InfoBuilderFunc
// WithParam sets a custom param
WithParam(k string, v any) AppError
// WithTransParam sets a custom param with value to be translated when build info
WithTransParam(k string, v string) AppError
// WithCause sets cause of the error
WithCause(err error) AppError
// WithDebug sets debug message (used for debug purpose)
WithDebug(format string, args ...any) AppError
// WithCustomConfig sets custom config for the error
WithCustomConfig(*ErrorConfig) AppError
// WithCustomBuilder sets custom info builder
WithCustomBuilder(InfoBuilderFunc) AppError
// Build builds error info
Build(Language, ...InfoBuilderOption) *InfoBuilderResult
}
AppError is designed to be used as base error type for any error in an application. An AppError can carry much extra information such as `cause`, `debug log`, and stack trace. It also supports translating the message into a specific language.
type Config ¶
type Config struct {
// Debug flag indicates debug mode (default: `false`).
// If `false`, app error `debug` string can't be set.
Debug bool
// WrapFunc to wrap an error with adding stack trace (default: `nil`).
// This function is nil by default which means the library will use default value
// which is function Wrap from `github.com/go-errors/errors`.
WrapFunc func(error) error
// MaxStackDepth max stack depth (default: `50`).
// If WrapFunc is set with custom value, this config has no effect.
MaxStackDepth int
// DefaultLanguage default language (default: `LanguageEn`)
DefaultLanguage Language
// TranslationFunc function to translate message into a specific language (default: `nil`)
TranslationFunc TranslationFunc
// FallbackToErrorContentOnMissingTranslation indicates fallback to error content
// when translation failed (default: `true`).
// If `false`, when translation fails, the output message will be empty.
FallbackToErrorContentOnMissingTranslation bool
// MultiErrorSeparator separator of multiple error strings (default: `\n`)
MultiErrorSeparator string
// DefaultErrorStatus default status for error if unset (default: `500`)
DefaultErrorStatus int
// DefaultValidationErrorStatus default status for validation error if unset (default: `400`)
DefaultValidationErrorStatus int
// DefaultValidationErrorCode default code for validation error if unset (default: `ErrValidation`)
DefaultValidationErrorCode string
// DefaultLogLevel default log level for errors if unset (default: `LogLevelNone`)
DefaultLogLevel LogLevel
}
Config to provide global config for the library
type ErrorConfig ¶
type ErrorConfig struct {
Status int
Code string
Title string
LogLevel LogLevel
TransKey string
Extra any
}
ErrorConfig configuration of an error to be used when build error info
func GetErrorConfig ¶
func GetErrorConfig(err error) *ErrorConfig
GetErrorConfig gets global mapping config of an error if set
type ErrorInfo ¶
type ErrorInfo struct {
Status int `json:"status,omitempty"`
Code string `json:"code,omitempty"`
Source any `json:"source,omitempty"`
Title string `json:"title,omitempty"`
Message string `json:"message,omitempty"`
Cause string `json:"cause,omitempty"`
Debug string `json:"debug,omitempty"`
LogLevel LogLevel `json:"logLevel,omitempty"`
InnerErrors []*ErrorInfo `json:"errors,omitempty"`
AssociatedError error `json:"-"`
}
ErrorInfo stores error information which can be used to return to client
type InfoBuilderConfig ¶
type InfoBuilderConfig struct {
ErrorConfig ErrorConfig
InfoBuilderFunc InfoBuilderFunc
Language Language
ErrorSeparator string
TranslationFunc TranslationFunc
TranslateTitle bool
FallbackToErrorContentOnMissingTranslation bool
}
InfoBuilderConfig config used to build error info
type InfoBuilderFunc ¶
type InfoBuilderFunc func(AppError, *InfoBuilderConfig) *InfoBuilderResult
InfoBuilderFunc custom info builder function
type InfoBuilderOption ¶
type InfoBuilderOption func(*InfoBuilderConfig)
InfoBuilderOption config setter for building error info
func InfoBuilderOptionCustomBuilder ¶
func InfoBuilderOptionCustomBuilder(infoBuilderFunc InfoBuilderFunc) InfoBuilderOption
InfoBuilderOptionCustomBuilder sets custom info builder
func InfoBuilderOptionCustomConfig ¶
func InfoBuilderOptionCustomConfig(errorConfig ErrorConfig) InfoBuilderOption
InfoBuilderOptionCustomConfig sets custom config
func InfoBuilderOptionFallbackContent ¶
func InfoBuilderOptionFallbackContent(fallbackToContent bool) InfoBuilderOption
InfoBuilderOptionFallbackContent sets flag fallback to error content on missing translation
func InfoBuilderOptionSeparator ¶
func InfoBuilderOptionSeparator(errorSeparator string) InfoBuilderOption
InfoBuilderOptionSeparator sets custom content separator
func InfoBuilderOptionTranslateTitle ¶ added in v0.5.1
func InfoBuilderOptionTranslateTitle(translateTitle bool) InfoBuilderOption
InfoBuilderOptionTranslateTitle sets flag indicating title translation
func InfoBuilderOptionTranslationFunc ¶
func InfoBuilderOptionTranslationFunc(translationFunc TranslationFunc) InfoBuilderOption
InfoBuilderOptionTranslationFunc sets custom translation function
type InfoBuilderResult ¶
type InfoBuilderResult struct {
// ErrorInfo result information of error which can be used to return to client
ErrorInfo *ErrorInfo
// TransMissingKeys missing keys when translate
TransMissingKeys []string
// TransMissingMainKey is set `true` if the main message key is missing
TransMissingMainKey bool
}
InfoBuilderResult result of building process
func Build ¶
func Build(err error, lang Language, options ...InfoBuilderOption) *InfoBuilderResult
Build builds error info
type Language ¶
type Language any
Language represents a language. Language values can be anything and can be set by client code. For example, Language("string") or Language(language.Tag from "golang.org/x/text/language").
type LogLevel ¶
type LogLevel string
LogLevel represents log level set for an error. You can use LogLevel to report the level of an error to external services such as Sentry or Rollbar.
type MultiError ¶
MultiError can handle multiple underlying AppErrors
func AsMultiError ¶
func AsMultiError(err AppError) MultiError
AsMultiError converts AppError to MultiError
func NewMultiError ¶
func NewMultiError(errs ...AppError) MultiError
NewMultiError creates a MultiError with wrapping the given errors
type TranslationFunc ¶
type ValidationError ¶
type ValidationError MultiError
func NewValidationError ¶
func NewValidationError(errs ...AppError) ValidationError
NewValidationError creates a validation error for the given validation error items
func NewValidationErrorWithInfoBuilder ¶
func NewValidationErrorWithInfoBuilder(infoBuilder InfoBuilderFunc, errs ...error) ValidationError