github.com/chain5j/chain5j-pkg@v1.0.7/errorx/errorx.go (about)

     1  // Package errorx
     2  //
     3  // @author: xwc1125
     4  package errorx
     5  
     6  import (
     7  	"fmt"
     8  
     9  	"github.com/chain5j/chain5j-pkg/codec/json"
    10  )
    11  
    12  type Error interface {
    13  	Error() string  // 错误信息
    14  	ErrorCode() int // 错误码
    15  }
    16  
    17  type RespInfo struct {
    18  	Code    int         `json:"code"`
    19  	Message string      `json:"message"`
    20  	Data    interface{} `json:"data,omitempty"`
    21  }
    22  
    23  // Errorf returns Error(code, fmt.Sprintf(format, a...)).
    24  func Errorf(code int, format string, a ...interface{}) RespInfo {
    25  	return Errorw(code, fmt.Sprintf(format, a...))
    26  }
    27  
    28  func Errorw(code int, msg string) RespInfo {
    29  	return RespInfo{
    30  		Code:    code,
    31  		Message: msg,
    32  		Data:    nil,
    33  	}
    34  }
    35  
    36  func Errordf(code int, data interface{}, format string, a ...interface{}) RespInfo {
    37  	return Errord(code, data, fmt.Sprintf(format, a...))
    38  }
    39  
    40  func Errord(code int, data interface{}, msg string) RespInfo {
    41  	return RespInfo{
    42  		Code:    code,
    43  		Message: msg,
    44  		Data:    data,
    45  	}
    46  }
    47  
    48  func (err RespInfo) String() string {
    49  	marshal, _ := json.Marshal(err)
    50  	return string(marshal)
    51  }
    52  
    53  func (err RespInfo) Error() string {
    54  	var errMsg string
    55  	if err.Message == "" {
    56  		errMsg = fmt.Sprintf("code=%d", err.Code)
    57  	} else {
    58  		errMsg = fmt.Sprintf("code=%d, msg=%s", err.Code, err.Message)
    59  	}
    60  	if err.Data != nil {
    61  		errMsg = fmt.Sprintf("%s, data=%v", errMsg, err.Data)
    62  	}
    63  	return errMsg
    64  }
    65  
    66  func (err RespInfo) ErrorCode() int {
    67  	return err.Code
    68  }
    69  
    70  func (err RespInfo) ErrorData() interface{} {
    71  	return err.Data
    72  }