Returning from Defer in Go
You're encountering an issue where you want to return an error if a function panics in Go. Here's an analysis and a fix for your code:
func getReport(filename string) (rep report, err error) { rep.data = make(map[string]float64) defer func() { if r := recover(); r != nil { fmt.Println("Recovered in f", r) switch x := r.(type) { case string: err = errors.New(x) case error: err = x default: err = errors.New("Unknown panic") } rep = nil // Invalidate rep } }() panic("Report format not recognized.") // rest of the getReport function... }
Concept of Panic and Defer
Modifications in the Code:
With these changes, your getReport function will return an error if it panics due to an invalid report format. The error message will be either the panic value (if a string) or a generic error indicating an unknown panic.
Disclaimer: All resources provided are partly from the Internet. If there is any infringement of your copyright or other rights and interests, please explain the detailed reasons and provide proof of copyright or rights and interests and then send it to the email: [email protected] We will handle it for you as soon as possible.
Copyright© 2022 湘ICP备2022001581号-3