bouncer/internal/command/api/apierr/wrap.go

92 lines
1.3 KiB
Go
Raw Normal View History

2023-04-24 20:52:12 +02:00
package apierr
import (
"github.com/pkg/errors"
"gitlab.com/wpetit/goweb/api"
)
func Wrap(err error) error {
apiErr := &api.Error{}
if !errors.As(err, &apiErr) {
return err
}
switch apiErr.Code {
case api.ErrCodeInvalidFieldValue:
return wrapInvalidFieldValueErr(apiErr)
default:
return wrapApiErrorWithMessage(apiErr)
}
}
func wrapApiErrorWithMessage(err *api.Error) error {
data, ok := err.Data.(map[string]any)
if !ok {
return err
}
rawMessage, exists := data["message"]
if !exists {
return err
}
message, ok := rawMessage.(string)
if !ok {
return err
}
return errors.Wrapf(err, message)
}
func wrapInvalidFieldValueErr(err *api.Error) error {
data, ok := err.Data.(map[string]any)
if !ok {
return err
}
rawFields, exists := data["Fields"]
if !exists {
return err
}
fields, ok := rawFields.([]any)
if !ok {
return err
}
var (
field string
rule string
)
if len(fields) == 0 {
return err
}
firstField, ok := fields[0].(map[string]any)
if !ok {
return err
}
param, ok := firstField["Param"].(string)
if !ok {
return err
}
tag, ok := firstField["Tag"].(string)
if !ok {
return err
}
fieldName, ok := firstField["Field"].(string)
if !ok {
return err
}
field = fieldName
rule = tag + "=" + param
return errors.Wrapf(err, "server expected field '%s' to match rule '%s'", field, rule)
}