Home > Article > Backend Development > How to Return an Error if a Go Function Panics?
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.
The above is the detailed content of How to Return an Error if a Go Function Panics?. For more information, please follow other related articles on the PHP Chinese website!