github.com/aaabigfish/gopkg@v1.1.0/ecode/ecode.go (about)

     1  package ecode
     2  
     3  import (
     4  	"errors"
     5  	"fmt"
     6  	"strconv"
     7  )
     8  
     9  var (
    10  	_codes = map[string]struct{}{}
    11  )
    12  
    13  type ECode string
    14  
    15  // New create a ecode
    16  func New(e int) ECode {
    17  	if e <= 0 {
    18  		panic("ecode must > 0")
    19  	}
    20  
    21  	return add(strconv.Itoa(e))
    22  }
    23  
    24  func add(e string) ECode {
    25  	if _, ok := _codes[e]; ok {
    26  		panic(fmt.Sprintf("ecode: %s already exist", e))
    27  	}
    28  	_codes[e] = struct{}{}
    29  	return Code(e)
    30  }
    31  
    32  func (e ECode) Ok() bool {
    33  	return string(e) == string(EcodeOk)
    34  }
    35  
    36  func (e ECode) Fail() bool {
    37  	return !e.Ok()
    38  }
    39  
    40  func (e ECode) Error() string {
    41  	return string(e)
    42  }
    43  
    44  func (e ECode) String() string {
    45  	return string(e)
    46  }
    47  
    48  // Message return error message
    49  func (e ECode) Message() string {
    50  	if msg, ok := messages[e.Int()]; ok {
    51  		return msg
    52  	}
    53  
    54  	return e.Error()
    55  }
    56  
    57  // Code from string to ecode
    58  func Code(e string) ECode { return ECode(e) }
    59  
    60  // Int from ecode to int
    61  func (e ECode) Int() int {
    62  	i, _ := strconv.Atoi(e.String())
    63  	return i
    64  }
    65  
    66  func (e ECode) Is(err error) bool {
    67  	return errors.Is(e, err)
    68  }