Files
mtusi2026lab4-fork/backend/internal/domain/errors.go
T

123 lines
4.2 KiB
Go
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
package domain
import (
"errors"
"fmt"
)
type ErrorCode string
const (
CodeInvalidRequest ErrorCode = "invalid_request"
CodeUnauthorized ErrorCode = "unauthorized"
CodeNotFound ErrorCode = "not_found"
CodeConflict ErrorCode = "conflict"
CodeUnsupportedMediaType ErrorCode = "unsupported_media_type"
CodeInternalError ErrorCode = "internal_error"
CodeUnavailable ErrorCode = "unavailable"
CodePayloadTooLarge ErrorCode = "payload_too_large"
)
var (
ErrNotFound = errors.New("не найдено")
ErrAlreadyExists = errors.New("уже существует")
ErrInvalidInput = errors.New("некорректные данные")
ErrUnauthorized = errors.New("требуется аутентификация")
ErrUnsupportedMediaType = errors.New("неподдерживаемый тип содержимого")
ErrUnavailable = errors.New("сервис недоступен")
ErrPayloadTooLarge = errors.New("превышен допустимый размер")
)
type NotFoundError struct {
Entity string
ID string
}
func (e *NotFoundError) Error() string {
return fmt.Sprintf("%s с id %q не найден", e.Entity, e.ID)
}
func (e *NotFoundError) Unwrap() error { return ErrNotFound }
func (e *NotFoundError) Code() ErrorCode { return CodeNotFound }
type AlreadyExistsError struct {
Entity string
Field string
Value string
}
func (e *AlreadyExistsError) Error() string {
return fmt.Sprintf("%s с %s %q уже существует", e.Entity, e.Field, e.Value)
}
func (e *AlreadyExistsError) Unwrap() error { return ErrAlreadyExists }
func (e *AlreadyExistsError) Code() ErrorCode { return CodeConflict }
type IdempotencyConflictError struct {
Key string
}
func (e *IdempotencyConflictError) Error() string {
return "Idempotency-Key " + e.Key + " уже использован с другим телом запроса"
}
func (e *IdempotencyConflictError) Unwrap() error { return ErrAlreadyExists }
func (e *IdempotencyConflictError) Code() ErrorCode { return CodeConflict }
type ValidationError struct {
Field string
Message string
}
func (e *ValidationError) Error() string {
return fmt.Sprintf("ошибка валидации поля %q: %s", e.Field, e.Message)
}
func (e *ValidationError) Unwrap() error { return ErrInvalidInput }
func (e *ValidationError) Code() ErrorCode { return CodeInvalidRequest }
type UnauthorizedError struct {
Reason string // для логов; в JSON не попадает
}
func (e *UnauthorizedError) Error() string {
return "требуется аутентификация"
}
func (e *UnauthorizedError) Unwrap() error { return ErrUnauthorized }
func (e *UnauthorizedError) Code() ErrorCode { return CodeUnauthorized }
type UnsupportedMediaTypeError struct {
MediaType string
}
func (e *UnsupportedMediaTypeError) Error() string {
if e.MediaType == "" {
return "требуется Content-Type: application/json"
}
return fmt.Sprintf("неподдерживаемый Content-Type %q; требуется application/json", e.MediaType)
}
func (e *UnsupportedMediaTypeError) Unwrap() error { return ErrUnsupportedMediaType }
func (e *UnsupportedMediaTypeError) Code() ErrorCode { return CodeUnsupportedMediaType }
type UnavailableError struct{ Reason string }
func (e *UnavailableError) Error() string {
return "сервис временно недоступен"
}
func (e *UnavailableError) Unwrap() error { return ErrUnavailable }
func (e *UnavailableError) Code() ErrorCode { return CodeUnavailable }
// PayloadTooLargeError - 413. Лимит кладём в структуру, чтобы его можно
// было переиспользовать в тексте ошибки, если Message не задан.
// Message опционален: если пуст — формируется из Limit.
type PayloadTooLargeError struct {
Limit int64
Message string
}
func (e *PayloadTooLargeError) Error() string {
if e.Message != "" {
return e.Message
}
return fmt.Sprintf("превышен лимит %d байт", e.Limit)
}
func (e *PayloadTooLargeError) Unwrap() error { return ErrPayloadTooLarge }
func (e *PayloadTooLargeError) Code() ErrorCode { return CodePayloadTooLarge }