1、错误只在逻辑的最外层处理一次,底层只返回错误。
2、底层除了返回错误外,要对原始错误进行包装,增加错误信息、调用栈等这些有利于排查的上下文信息。
1、errors包:
//只附加新的信息
func WithMessage(err error, message string) error
如:
if err != nil {
errors.WithMessage(err, "could not read config")
}
//只附加调用堆栈信息
func WithStack(err error) error
//同时附加堆栈和信息
func Wrap(err error, message string) error
如:
if err != nil {
return errors.Wrap(err, "open failed")
}
// 返回包装错误对应的最原始错误
errors.Cause(err)
如:
fmt.Printf("original error: %T %v\n", errors.Cause(err), errors.Cause(err))
2、Err集中判断:
初始:
// 开车去商店
shopper, err := shopper.Drive(FuelNeededToGetToStore)
if nil != err {
log.Fatalf("could not complete shopping: %s", err)
}
// 买鸡蛋
shopper, err = shopper.BuyEggs(EggsRequired)
if nil != err {
log.Fatalf("could not complete shopping: %s", err)
}
// 买完鸡蛋开车回家
shopper, err = shopper.Drive(FuelNeededToGetHome)
if nil != err {
log.Fatalf("could not complete shopping: %s", err)
}
只打印不返回的err集中判断
func main(){
shopper, err := shopper.Drive(FuelNeededToGetToStore)
FatalIfErrNotNil(err)
shopper, err = shopper.BuyEggs(EggsRequired)
FatalIfErrNotNil(err)
shopper, err = shopper.Drive(FuelNeededToGetHome)
FatalIfErrNotNil(err)
}
func FatalIfErrNotNil(err error) {
if nil != err {
log.Fatalf("could not complete shopping: %s", err)
}
}
3、责任链迭代变换
func main(){
driveToStore := Flavorize(Drive, FuelNeededToGetToStore)
buyEggs := Flavorize(BuyEggs, EggsRequired)
driveHome := Flavorize(Drive, FuelNeededToGetHome)
shopper, err := ProcessSteps(shopper,
driveToStore,
buyEggs,
driveHome,
)
if nil != err {
log.Fatalf("could not complete shopping: %s", err)
}
}
func ProcessSteps(s Shopper, steps ...func(Shopper) (Shopper, error)) (Shopper, error) {
for _, step := range steps {
var err error
s, err = step(s)
if nil != err {
return s, err
}
}
return s, nil
}
func Flavorize(f func(Shopper, int) (Shopper, error), arg int) func(Shopper) (Shopper, error) {
return func(s Shopper) (Shopper, error) {
return f(s, arg)
}
}
4、使用defer消除冗余
func writeConfig(data interface{}) (err error) {
defer func() {
if err != nil {
err = errors.WithMessage(err, "writing configuration")
}
}()
b, err := json.Marshal(data)
if err != nil {
return err
}
if err = ioutil.WriteFile("config.json", b, 0644); err != nil {
return err
}
return
}
5、