In Go, error handling can become tedious when dealing with numerous potential errors. For instance, consider the following code:
aJson, err1 := json.Marshal(a) bJson, err2 := json.Marshal(b) cJson, err3 := json.Marshal(c) dJson, err4 := json.Marshal(d) eJson, err5 := json.Marshal(e) fJson, err6 := json.Marshal(f) gJson, err4 := json.Marshal(g) if err1 != nil { return err1 } else if err2 != nil { return err2 } else if err3 != nil { return err3 } else if err4 != nil { return err4 } else if err5 != nil { return err5 } else if err5 != nil { return err5 } else if err6 != nil { return err6 }
This code's error handling is highly repetitive and difficult to maintain. A cleaner and more efficient approach involves using a closure to handle all errors at once:
var err error f := func(dest *D, src S) bool { *dest, err = json.Marshal(src) return err == nil } // EDIT: removed () f(&aJson, a) && f(&bJson, b) && f(&cJson, c) && f(&dJson, d) && f(&eJson, e) && f(&fJson, f) && f(&gJson, g) return err
This function pointer, f, encapsulates the error handling logic and simplifies the main function by chaining calls and returning the first non-nil error encountered. By implementing this technique, you achieve more concise and elegant error handling.
The above is the detailed content of How Can I Handle Multiple Errors Gracefully in Go?. For more information, please follow other related articles on the PHP Chinese website!