github.com/wfusion/gofusion@v1.1.14/http/error.go (about)

     1  package http
     2  
     3  import (
     4  	"context"
     5  	"strconv"
     6  
     7  	"github.com/gin-gonic/gin"
     8  
     9  	"github.com/wfusion/gofusion/common/utils"
    10  	"github.com/wfusion/gofusion/i18n"
    11  
    12  	fusCtx "github.com/wfusion/gofusion/context"
    13  )
    14  
    15  var (
    16  	errParam Errcode = -1
    17  )
    18  
    19  type Errcode int
    20  
    21  // String Here, i18n cannot be used for localization,
    22  // because in Localize, since the code is of string type, the process of doing toString will lead to stack overflow.
    23  func (e Errcode) String() (r string) {
    24  	return strconv.Itoa(int(e))
    25  }
    26  func (e Errcode) Error() (r string) {
    27  	return I18n.Localize(e)
    28  }
    29  
    30  type errOption struct {
    31  	msg   string
    32  	langs []string
    33  	param map[string]any
    34  }
    35  
    36  func Langs(c *gin.Context) utils.OptionFunc[errOption] {
    37  	return func(e *errOption) {
    38  		e.langs = langs(c)
    39  	}
    40  }
    41  
    42  func Param(param map[string]any) utils.OptionFunc[errOption] {
    43  	return func(e *errOption) {
    44  		e.param = param
    45  	}
    46  }
    47  
    48  func Msg(msg string) utils.OptionFunc[errOption] {
    49  	return func(e *errOption) {
    50  		e.msg = msg
    51  	}
    52  }
    53  
    54  // Err customized message
    55  func Err(c *gin.Context, code Errcode, opts ...utils.OptionExtender) error {
    56  	opt := utils.ApplyOptions[errOption](opts...)
    57  	if len(opt.langs) == 0 {
    58  		opt.langs = langs(c)
    59  	}
    60  	return &bizErr{
    61  		code:      code,
    62  		errOption: opt,
    63  	}
    64  }
    65  
    66  // ErrCtx customized message
    67  func ErrCtx(ctx context.Context, code Errcode, opts ...utils.OptionExtender) error {
    68  	opt := utils.ApplyOptions[errOption](opts...)
    69  	if len(opt.langs) == 0 {
    70  		opt.langs = fusCtx.GetLangs(ctx)
    71  	}
    72  	return &bizErr{
    73  		code:      code,
    74  		errOption: opt,
    75  	}
    76  }
    77  
    78  type bizErr struct {
    79  	*errOption
    80  	code Errcode
    81  }
    82  
    83  func (b *bizErr) Error() (r string) {
    84  	if b.msg != "" {
    85  		return b.msg
    86  	}
    87  	return I18n.Localize(b.code, i18n.Langs(b.langs), i18n.Param(b.param))
    88  }