1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192 |
- package frame
- import (
- "github.com/druidcaesa/gotool"
- "github.com/go-playground/validator/v10"
- "reflect"
- )
- const (
- BUSINESS_CODE = 500 //业务错误
- SQL_CODE = 501 //业务错误
- )
- type Exception struct {
- Status int
- Msg string
- }
- func Throw(code int, msg string) {
- panic(Exception{
- Status: code,
- Msg: msg,
- })
- }
- func CheckSqlErr(err error) {
- if err != nil {
- Throw(SQL_CODE, err.Error())
- }
- }
- func CheckErr(code int, err error) {
- if err != nil {
- Throw(code, err.Error())
- }
- }
- func CheckBusinessErr(err error) {
- if err != nil {
- Throw(BUSINESS_CODE, err.Error())
- }
- }
- func CheckEmpty(str, msg string) {
- if gotool.StrUtils.HasEmpty(str) {
- Throw(BUSINESS_CODE, msg)
- }
- }
- func CheckNil(ptr interface{}, msg string) {
- if ptr == nil {
- Throw(BUSINESS_CODE, msg)
- }
- }
- func CheckNotNil(ptr interface{}, msg string) {
- if ptr != nil {
- Throw(BUSINESS_CODE, msg)
- }
- }
- func CheckFalse(bl bool, msg string) {
- if !bl {
- Throw(BUSINESS_CODE, msg)
- }
- }
- func CheckTrue(bl bool, msg string) {
- if bl {
- Throw(BUSINESS_CODE, msg)
- }
- }
- // GetError 自定义错误消息
- func GetError(errs validator.ValidationErrors, r interface{}) string {
- s := reflect.TypeOf(r)
- if s.Kind() == reflect.Ptr { //处理指针
- s = s.Elem()
- }
- for _, fieldError := range errs {
- filed, _ := s.FieldByName(fieldError.Field())
- errTag := fieldError.Tag() + "_msg"
- // 获取对应binding得错误消息
- errTagText := filed.Tag.Get(errTag)
- // 获取统一错误消息
- errText := filed.Tag.Get("msg")
- if errTagText != "" {
- return errTagText
- }
- if errText != "" {
- return errText
- }
- return fieldError.Field() + ":" + fieldError.Tag()
- }
- return ""
- }
|