github.com/binbinly/pkg@v0.0.11-0.20240321014439-f4fbf666eb0f/errno/errno.go (about)

     1  package errno
     2  
     3  import (
     4  	"fmt"
     5  	"net/http"
     6  )
     7  
     8  var _toStatus = map[int]int{
     9  	Success.Code():               http.StatusOK,
    10  	ErrInternalServer.Code():     http.StatusInternalServerError,
    11  	ErrNotFound.Code():           http.StatusNotFound,
    12  	ErrInvalidParam.Code():       http.StatusBadRequest,
    13  	ErrToken.Code():              http.StatusUnauthorized,
    14  	ErrInvalidToken.Code():       http.StatusUnauthorized,
    15  	ErrTokenTimeout.Code():       http.StatusUnauthorized,
    16  	ErrTooManyRequests.Code():    http.StatusTooManyRequests,
    17  	ErrServiceUnavailable.Code(): http.StatusServiceUnavailable,
    18  }
    19  
    20  // Error 返回错误码和消息的结构体
    21  type Error struct {
    22  	code    int
    23  	msg     string
    24  	details []string
    25  }
    26  
    27  // NewError 实例化
    28  func NewError(code int, msg string) *Error {
    29  	return &Error{code: code, msg: msg}
    30  }
    31  
    32  // Error 获取错误信息
    33  func (e *Error) Error() string {
    34  	return fmt.Sprintf("code:%d, msg::%s", e.Code(), e.Msg())
    35  }
    36  
    37  // Code 获取code
    38  func (e *Error) Code() int {
    39  	return e.code
    40  }
    41  
    42  // Msg 获取msg
    43  func (e *Error) Msg() string {
    44  	return e.msg
    45  }
    46  
    47  // Details 获取details
    48  func (e *Error) Details() []string {
    49  	return e.details
    50  }
    51  
    52  // WithDetails 设置details数据
    53  func (e *Error) WithDetails(details ...string) *Error {
    54  	newError := *e
    55  	newError.details = []string{}
    56  	for _, d := range details {
    57  		newError.details = append(newError.details, d)
    58  	}
    59  
    60  	return &newError
    61  }
    62  
    63  // StatusCode 状态码
    64  func (e *Error) StatusCode() int {
    65  	if c, ok := _toStatus[e.code]; ok {
    66  		return c
    67  	}
    68  
    69  	return http.StatusBadRequest
    70  }
    71  
    72  // Err represents an error
    73  type Err struct {
    74  	Code    int
    75  	Message string
    76  	Err     error
    77  }
    78  
    79  // Error 格式化
    80  func (e *Err) Error() string {
    81  	return fmt.Sprintf("Err - code: %d, message: %s, error: %s", e.Code, e.Message, e.Err)
    82  }
    83  
    84  // DecodeErr 对错误进行解码,返回错误code和错误提示
    85  func DecodeErr(err error) (int, string) {
    86  	if err == nil {
    87  		return Success.code, Success.msg
    88  	}
    89  
    90  	switch typed := err.(type) {
    91  	case *Err:
    92  		return typed.Code, typed.Message
    93  	case *Error:
    94  		return typed.code, typed.msg
    95  	default:
    96  	}
    97  
    98  	return ErrInternalServer.Code(), err.Error()
    99  }