errors

package
v0.0.0-...-7827b3b Latest Latest
Warning

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

Go to latest
Published: Dec 18, 2025 License: MIT Imports: 11 Imported by: 0

Documentation

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

func GRPCRateLimited

func GRPCRateLimited(retryAfter time.Duration) error

GRPCRateLimited — готовый gRPC error с RetryInfo + ErrorInfo(reason).

func HTTPStatus

func HTTPStatus(code codes.Code) int

func IsDomainError

func IsDomainError(err error) bool

Types

type DomainError

type DomainError struct {
	Field  string
	Reason string
}

одиночная доменная ошибка (инвариант)

func DomainInvariant

func DomainInvariant(field, reason string) DomainError

func (DomainError) Error

func (e DomainError) Error() string

type DomainErrors

type DomainErrors []DomainError

батч доменных ошибок (несколько инвариантов за раз)

func (DomainErrors) Error

func (es DomainErrors) Error() string

type ErrorResponse

type ErrorResponse struct {
	Code       codes.Code        `json:"code"`
	Reason     Reason            `json:"reason,omitempty"`
	Domain     string            `json:"domain,omitempty"` // опционально: заполняется сервисом (e.g. "auth-service")
	Message    string            `json:"message"`
	Details    map[string]string `json:"details,omitempty"`
	Violations []FieldViolation  `json:"violations,omitempty"`
}

func Aborted

func Aborted() ErrorResponse

func AlreadyExists

func AlreadyExists() ErrorResponse

func Conflict

func Conflict(field, value string) ErrorResponse

Conflict(field,value) -> 409/AlreadyExists.

func ConvertDomainErrorsToValidation

func ConvertDomainErrorsToValidation(errs DomainErrors) ErrorResponse

func ConvertDomainToValidation

func ConvertDomainToValidation(err error) ErrorResponse

func DataLoss

func DataLoss() ErrorResponse

func DeadlineExceeded

func DeadlineExceeded() ErrorResponse

func FailedPrecondition

func FailedPrecondition() ErrorResponse

func Forbidden

func Forbidden(action, resource string) ErrorResponse

Forbidden для RBAC.

func FromGRPC

func FromGRPC(err error) ErrorResponse

func FromPlayground

func FromPlayground(err play.ValidationErrors, tagToReason map[string]string) ErrorResponse

FromPlayground — адаптер go-playground/validator -> InvalidArgument + Violations. Пытаемся получить вложенный путь поля: StructNamespace() -> (fallback) Namespace() без корня.

func Internal

func Internal() ErrorResponse

func InvalidArgument

func InvalidArgument() ErrorResponse

func New

func New(message string, code codes.Code, details map[string]string) ErrorResponse

func Newf

func Newf(code codes.Code, reason, format string, a ...any) ErrorResponse

Newf — форматированный конструктор с reason.

func NotFound

func NotFound() ErrorResponse

func NotFoundID

func NotFoundID(resource, id string) ErrorResponse

NotFoundID(resource,id).

func NotFoundWith

func NotFoundWith(resourceKey, value string) ErrorResponse

func OutOfRange

func OutOfRange() ErrorResponse

func PermissionDenied

func PermissionDenied() ErrorResponse

func Precondition

func Precondition(reason string, details map[string]string) ErrorResponse

Precondition(reason, details) -> 412/FailedPrecondition.

func RateLimited

func RateLimited(retryAfter time.Duration) ErrorResponse

RateLimited — с machine-friendly задержкой в мс.

func ResourceExhausted

func ResourceExhausted() ErrorResponse

func To

func To(code codes.Code, reason, msg string) ErrorResponse

func ToErrorResponse

func ToErrorResponse(err error) ErrorResponse

ToErrorResponse — унифицирует любую ошибку до ErrorResponse (без привязки к транспорту).

func ToValidation

func ToValidation(field, reason string) ErrorResponse

Хелперы, если нужно точечно.

func Unauthenticated

func Unauthenticated() ErrorResponse

func Unauthorized

func Unauthorized(scheme, realm string) ErrorResponse

Unauthorized с подсказками для клиента.

func Unavailable

func Unavailable() ErrorResponse

func Unimplemented

func Unimplemented() ErrorResponse

func Unknown

func Unknown() ErrorResponse

Фабричные функции (неизменяемые пресеты).

func Unsupported

func Unsupported(name, value string) ErrorResponse

func ValidationFields

func ValidationFields(fields map[string]string) ErrorResponse

Быстрые конструкторы частых кейсов

func ValidationViolations

func ValidationViolations(v []FieldViolation) ErrorResponse

func (ErrorResponse) Error

func (e ErrorResponse) Error() string

func (ErrorResponse) ToGRPC

func (e ErrorResponse) ToGRPC() error

func (ErrorResponse) ToHTTP

func (e ErrorResponse) ToHTTP(w http.ResponseWriter)

func (ErrorResponse) ToHTTPWithRetry

func (e ErrorResponse) ToHTTPWithRetry(w http.ResponseWriter, retryAfter time.Duration)

Helper: добавить Retry-After (сек) и вернуть тело ошибки.

func (ErrorResponse) ToString

func (e ErrorResponse) ToString() string

func (ErrorResponse) WithDetail

func (e ErrorResponse) WithDetail(k, v string) ErrorResponse

func (ErrorResponse) WithDetails

func (e ErrorResponse) WithDetails(m map[string]string) ErrorResponse

func (ErrorResponse) WithDomain

func (e ErrorResponse) WithDomain(d string) ErrorResponse

func (ErrorResponse) WithReason

func (e ErrorResponse) WithReason(r string) ErrorResponse

func (ErrorResponse) WithViolations

func (e ErrorResponse) WithViolations(v []FieldViolation) ErrorResponse

type FieldViolation

type FieldViolation struct {
	Field       string `json:"field"`
	Reason      string `json:"reason,omitempty"`
	Description string `json:"description,omitempty"`
}

func ViolationsFromMap

func ViolationsFromMap(m map[string]string) []FieldViolation

type Reason

type Reason string

Reason — стабильный машинный код (для фронта/аналитики/локализации).

Jump to

Keyboard shortcuts

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