error.go 1004 Bytes
Newer Older
kzkzzzz's avatar
kzkzzzz committed
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57
package errorx

import (
	"fmt"
	"github.com/go-playground/validator/v10"
	"gokratos-base/common/validate"
)

const (
	DefaultError = 500
	ParamsError  = 400
)

type ResponseError struct {
	Code int    `json:"code"`
	Msg  string `json:"msg"`
}

var _ error = &ResponseError{}

func (c *ResponseError) Error() string {
	return fmt.Sprintf("[%d]%s", c.Code, c.Msg)
}

func NewError(message string, code ...int) error {
	var c = DefaultError
	if len(code) > 0 {
		c = code[0]
	}
	e := &ResponseError{
		Code: c,
		Msg:  message,
	}
	return e
}

func ParseError(err error) (errorCode int, msg string) {
	switch v := err.(type) {
	case *ResponseError:
		errorCode = v.Code
		msg = v.Msg
	case validator.ValidationErrors:
		errorCode = ParamsError
		if len(v) > 0 {
			msg = v[0].Translate(validate.GrtTrans())
		} else {
			msg = v.Error()
		}
	case validator.FieldError:
		errorCode = ParamsError
		msg = v.Translate(validate.GrtTrans())
	default:
		errorCode = DefaultError
		msg = err.Error()
	}
	return
}