github.com/nyan233/littlerpc@v0.4.6-0.20230316182519-0c8d5c48abaf/core/protocol/error/std_error.go (about)

     1  package error
     2  
     3  import (
     4  	"encoding/json"
     5  	"github.com/nyan233/littlerpc/core/utils/convert"
     6  )
     7  
     8  type LStdError struct {
     9  	LCode    Code          `json:"code"`
    10  	LMessage string        `json:"message"`
    11  	LMores   []interface{} `json:"mores"`
    12  }
    13  
    14  func LNewStdError(code int, message string, mores ...interface{}) LErrorDesc {
    15  	return &LStdError{
    16  		LCode:    Code(code),
    17  		LMessage: message,
    18  		LMores:   mores,
    19  	}
    20  }
    21  
    22  func LWarpStdError(desc LErrorDesc, mores ...interface{}) LErrorDesc {
    23  	return &LStdError{
    24  		LCode:    Code(desc.Code()),
    25  		LMessage: desc.Message(),
    26  		LMores:   append(desc.Mores(), mores...),
    27  	}
    28  }
    29  
    30  func (L *LStdError) Code() int {
    31  	return int(L.LCode)
    32  }
    33  
    34  func (L *LStdError) Message() string {
    35  	return L.LMessage
    36  }
    37  
    38  func (L *LStdError) AppendMore(more interface{}) {
    39  	L.LMores = append(L.LMores, more)
    40  }
    41  
    42  func (L *LStdError) Mores() []interface{} {
    43  	return L.LMores
    44  }
    45  
    46  func (L *LStdError) Error() string {
    47  	bytes, err := json.Marshal(L)
    48  	if err != nil {
    49  		panic("json.Marshal failed : " + err.Error())
    50  	}
    51  	return convert.BytesToString(bytes)
    52  }
    53  
    54  func (L *LStdError) MarshalMores() ([]byte, error) {
    55  	return json.Marshal(L.LMores)
    56  }
    57  
    58  func (L *LStdError) UnmarshalMores(bytes []byte) error {
    59  	return json.Unmarshal(bytes, &L.LMores)
    60  }