github.com/machinefi/w3bstream@v1.6.5-rc9.0.20240426031326-b8c7c4876e72/pkg/depends/kit/httptransport/req_tsfm_bad_error.go (about)

     1  package httptransport
     2  
     3  import (
     4  	"net/http"
     5  
     6  	pkgerr "github.com/pkg/errors"
     7  
     8  	"github.com/machinefi/w3bstream/pkg/depends/kit/statusx"
     9  	vldterr "github.com/machinefi/w3bstream/pkg/depends/kit/validator/errors"
    10  )
    11  
    12  type BadRequestError interface {
    13  	EnableErrTalk()
    14  	SetMsg(msg string)
    15  	AddErr(err error, nameOrIdx ...interface{})
    16  }
    17  
    18  type badRequest struct {
    19  	errorFields statusx.ErrorFields
    20  	errTalk     bool
    21  	msg         string
    22  }
    23  
    24  func (e *badRequest) EnableErrTalk() { e.errTalk = true }
    25  
    26  func (e *badRequest) SetMsg(msg string) { e.msg = msg }
    27  
    28  func (e *badRequest) AddErr(err error, nameOrIdx ...interface{}) {
    29  	if len(nameOrIdx) > 1 {
    30  		e.errorFields = append(e.errorFields, &statusx.ErrorField{
    31  			In:    nameOrIdx[0].(string),
    32  			Field: vldterr.KeyPath(nameOrIdx[1:]).String(),
    33  			Msg:   err.Error(),
    34  		})
    35  	}
    36  }
    37  
    38  func (e *badRequest) Err() error {
    39  	if len(e.errorFields) == 0 {
    40  		return nil
    41  	}
    42  
    43  	msg := e.msg
    44  	if msg == "" {
    45  		msg = "invalid parameters"
    46  	}
    47  
    48  	err := statusx.Wrap(pkgerr.New(""), http.StatusBadRequest, "badRequest").
    49  		WithMsg(msg).
    50  		AppendErrorFields(e.errorFields...)
    51  
    52  	if e.errTalk {
    53  		err = err.EnableErrTalk()
    54  	}
    55  
    56  	return err
    57  }