Ally/War commands

This commit is contained in:
Ilia Denisov
2025-09-28 22:43:27 +03:00
parent 6510676237
commit 128d6862a7
14 changed files with 315 additions and 74 deletions
+76
View File
@@ -0,0 +1,76 @@
package error
import (
"fmt"
)
const (
ErrDummy int = -1
ErrStorageFailure int = 1000
ErrGameStateInvalid int = 2000
ErrInputUnknownHostRace int = 3000
ErrInputUnknownOpponentRace int = 3001
)
func errorText(code int) string {
switch code {
case ErrDummy:
return "Dummy"
case ErrStorageFailure:
return "Storage failure"
case ErrGameStateInvalid:
return "Invalid game state"
case ErrInputUnknownHostRace:
return "Host race name is unknown to this game"
case ErrInputUnknownOpponentRace:
return "Opponent race name is unknown to this game"
default:
return fmt.Sprintf("Undescribed error with code %d", code)
}
}
type GenericError struct {
code int
subject string
err error
}
func (ge GenericError) Error() string {
msg := errorText(ge.code)
if ge.subject != "" {
msg += ": " + ge.subject
}
if ge.err != nil {
msg = fmt.Errorf("%s: %w", msg, ge.err).Error()
}
return msg
}
func newGenericError(code int, arg ...any) error {
e := &GenericError{code: code}
if len(arg) > 0 {
i := 0
switch arg[i].(type) {
case error:
e.err = arg[i].(error)
i += 1
}
if len(arg) == i+2 {
e.subject = fmt.Sprintf(asString(arg[i]), arg[i+1:]...)
} else if len(arg) == i+1 {
e.subject = asString(arg[i])
}
}
return *e
}
func asString(v any) string {
switch s := v.(type) {
case string:
return s
default:
return fmt.Sprint(v)
}
}
+27
View File
@@ -0,0 +1,27 @@
package error
import (
"errors"
"strconv"
"testing"
"github.com/stretchr/testify/assert"
)
func TestNewGenericError(t *testing.T) {
for i, tc := range []struct {
arg []any
message string
}{
{arg: []any{"Foo"}, message: "Dummy: Foo"},
{arg: []any{"Foo%s", "Bar"}, message: "Dummy: FooBar"},
{arg: []any{errors.New("Error")}, message: "Dummy: Error"},
{arg: []any{errors.New("Error"), "Foo"}, message: "Dummy: Foo: Error"},
{arg: []any{errors.New("Error"), "Foo%s", "Bar"}, message: "Dummy: FooBar: Error"},
} {
t.Run(strconv.Itoa(i), func(t *testing.T) {
err := newGenericError(ErrDummy, tc.arg...)
assert.EqualError(t, err, tc.message)
})
}
}
+9
View File
@@ -0,0 +1,9 @@
package error
func NewHostRaceUnknownError(arg ...any) error {
return newGenericError(ErrInputUnknownHostRace, arg...)
}
func NewOpponentRaceUnknownError(arg ...any) error {
return newGenericError(ErrInputUnknownOpponentRace, arg...)
}
+5
View File
@@ -0,0 +1,5 @@
package error
func NewRepoError(arg ...any) error {
return newGenericError(ErrStorageFailure, arg...)
}
+5
View File
@@ -0,0 +1,5 @@
package error
func NewGameStateError(arg ...any) error {
return newGenericError(ErrGameStateInvalid, arg...)
}