This repository has been archived on 2024-04-06. You can view files and clone it, but cannot push or open issues or pull requests.
core-old/internal/domain/error.go
Dawid Wysokiński 60d6dc1423
All checks were successful
continuous-integration/drone/push Build is passing
feat: add SliceValidationError
2023-02-13 06:19:30 +01:00

131 lines
2.2 KiB
Go

package domain
import (
"errors"
"fmt"
)
var (
ErrNothingToUpdate = errors.New("nothing to update")
ErrUnsupportedSortBy = errors.New("unsupported sort by")
)
type ErrorCode uint8
const (
ErrorCodeUnknown ErrorCode = iota
ErrorCodeEntityNotFound
ErrorCodeValidationError
)
func (e ErrorCode) String() string {
switch e {
case ErrorCodeEntityNotFound:
return "entity-not-found"
case ErrorCodeValidationError:
return "validation-error"
case ErrorCodeUnknown:
fallthrough
default:
return "internal-server-error"
}
}
type Error interface {
error
// UserError is a message that is returned to a user in, for example, an http response.
UserError() string
Code() ErrorCode
}
type ValidationError struct {
Field string
Err error
}
func (e ValidationError) Error() string {
return fmt.Sprintf("%s: %s", e.Field, e.Err)
}
func (e ValidationError) UserError() string {
return e.Error()
}
func (e ValidationError) Code() ErrorCode {
return ErrorCodeValidationError
}
func (e ValidationError) Unwrap() error {
return e.Err
}
type SliceValidationError struct {
Field string
Index int
Err error
}
func (e SliceValidationError) Error() string {
return fmt.Sprintf("%s[%d]: %s", e.Field, e.Index, e.Err)
}
func (e SliceValidationError) UserError() string {
return e.Error()
}
func (e SliceValidationError) Code() ErrorCode {
return ErrorCodeValidationError
}
func (e SliceValidationError) Unwrap() error {
return e.Err
}
type MaxError struct {
Max int
}
func (e MaxError) Error() string {
return fmt.Sprintf("must be no greater than %d", e.Max)
}
func (e MaxError) UserError() string {
return e.Error()
}
func (e MaxError) Code() ErrorCode {
return ErrorCodeValidationError
}
type MinError struct {
Min int
}
func (e MinError) Error() string {
return fmt.Sprintf("must be no less than %d", e.Min)
}
func (e MinError) UserError() string {
return e.Error()
}
func (e MinError) Code() ErrorCode {
return ErrorCodeValidationError
}
type MaxLengthError struct {
Max int
}
func (e MaxLengthError) Error() string {
return fmt.Sprintf("the length must be no more than %d", e.Max)
}
func (e MaxLengthError) UserError() string {
return e.Error()
}
func (e MaxLengthError) Code() ErrorCode {
return ErrorCodeValidationError
}