作者 yangfu

自定义 Error

package common
import "fmt"
type Error struct {
Code int
err error
}
func (e Error)Error()string{
if e.err==nil{
return ""
}
return e.err.Error()
}
func NewError(code int,e error)Error{
return Error{
Code:code,
err:e,
}
}
func NewErrorWithMsg(code int,msg string)Error{
return NewError(code,fmt.Errorf(msg))
}
... ...
package common
import (
"fmt"
"testing"
)
func Test_Error(t *testing.T){
e :=NewError(1,fmt.Errorf("%v","some error"))
t.Log(e,e.Code)
t.Logf("%s",e)
emsg :=NewErrorWithMsg(2,"some error")
t.Log(emsg,emsg.Code)
}
\ No newline at end of file
... ...