controller_resolver_error.go 1020 字节
package controllers

import (
	_ "embed"
	"github.com/linmadan/egglib-go/core/application"
	"github.com/linmadan/egglib-go/utils/json"
	"strings"
)

//go:embed errors.txt
var errorsData []byte

type CommErrorResolver struct {
	// TODO:LRU latest error list
	ErrorMapping map[string]string `json:"errorMapping"`
	errMapping   map[string]error  `json:"errorMapping"`
}

func (r *CommErrorResolver) Resolve(err error) error {
	if err == nil {
		return nil
	}
	errMsg := err.Error()
	if r.errMapping == nil {
		return err
	}
	if v, ok := r.errMapping[errMsg]; ok {
		return v
	}
	for k, v := range r.errMapping {
		if strings.Contains(errMsg, k) {
			return v
		}
	}
	return err
}

func NewCommErrorResolver() (*CommErrorResolver, error) {
	obj := &CommErrorResolver{errMapping: make(map[string]error)}
	err := json.Unmarshal(errorsData, obj)
	if err != nil {
		return nil, err
	}
	for k, v := range obj.ErrorMapping {
		obj.errMapping[k] = application.ThrowError(application.INTERNAL_SERVER_ERROR, v)
	}
	return obj, nil
}