Panic In Defer (ARCH5155)
Key go.logging.panic-in-defer · Severity error · Category logging
Panicking inside a defer block masks any in-flight error from the function body. This is the Go analogue of throwing from a finally block.
Incorrect
Section titled “Incorrect”func process(path string) error { f, err := os.Open(path) if err != nil { return err } defer func() { if err := f.Close(); err != nil { panic(err) // masks the real error } }() return parse(f)}Correct
Section titled “Correct”func process(path string) (err error) { f, err := os.Open(path) if err != nil { return err } defer func() { if cerr := f.Close(); cerr != nil && err == nil { err = cerr } }() return parse(f)}Assign the error to a named return value instead of panicking in defer, and don’t overwrite an existing error.