作者 yangfu

自定义 Error

  1 +package common
  2 +
  3 +import "fmt"
  4 +
  5 +type Error struct {
  6 + Code int
  7 + err error
  8 +}
  9 +
  10 +func (e Error)Error()string{
  11 + if e.err==nil{
  12 + return ""
  13 + }
  14 + return e.err.Error()
  15 +}
  16 +
  17 +func NewError(code int,e error)Error{
  18 + return Error{
  19 + Code:code,
  20 + err:e,
  21 + }
  22 +}
  23 +
  24 +func NewErrorWithMsg(code int,msg string)Error{
  25 + return NewError(code,fmt.Errorf(msg))
  26 +}
  1 +package common
  2 +
  3 +import (
  4 + "fmt"
  5 + "testing"
  6 +)
  7 +
  8 +func Test_Error(t *testing.T){
  9 + e :=NewError(1,fmt.Errorf("%v","some error"))
  10 + t.Log(e,e.Code)
  11 + t.Logf("%s",e)
  12 +
  13 + emsg :=NewErrorWithMsg(2,"some error")
  14 + t.Log(emsg,emsg.Code)
  15 +}