The art of programing It is often the case that there are many error blocks in the business logic. For example, call the following functions in sequence
func first() error {return nil}
func second() error {return nil}
func third() error {return nil}
func fourth() error {return nil}
func fifth() error {return nil}
How to write to judge ** error ** What? I was dizzy. .. ..
func Do() error {
var err error
if err = first(); err == nil {
if err = second(); err == nil {
if err = third(); err == nil {
if err = fourth(); err == nil {
if err = fifth(); err == nil {
return nil
}
}
}
}
}
return err
}
There are many flat people in the actual work,
func Do() error {
var err error
if err = first(); err != nil {
return err
}
if err = second(); err != nil {
return err
}
if err = third(); err != nil {
return err
}
if err = fourth(); err != nil {
return err
}
if err = fifth(); err != nil {
return err
}
return nil
}
Well, if you use ** panic **,
func Do2() (err error) {
defer func(){
if r:= recover() ; r!= nil{
err = fmt.Errorf("Error: %+v", r)
}
}()
first2()
second2()
third2()
fourth2()
fifth2()
return
}
Recommended Posts