From 5c681d508a1f1f1a69a60ef3ebb9e76e26bb628f Mon Sep 17 00:00:00 2001 From: Shantanu Kotambkar <52007797+skotambkar@users.noreply.github.com> Date: Thu, 29 Jul 2021 15:20:48 -0700 Subject: [PATCH] Handle error for defered file close call (#314) Handle error for defer close call --- ptr/generate.go | 14 +++++++++++--- 1 file changed, 11 insertions(+), 3 deletions(-) diff --git a/ptr/generate.go b/ptr/generate.go index 889d66f23..276fd8196 100644 --- a/ptr/generate.go +++ b/ptr/generate.go @@ -24,14 +24,22 @@ func main() { } } -func generateFile(filename string, tmplName string, types ptr.Scalars) error { +func generateFile(filename string, tmplName string, types ptr.Scalars) (err error) { f, err := os.Create(filename) if err != nil { return fmt.Errorf("failed to create %s file, %v", filename, err) } - defer f.Close() - if err := ptrTmpl.ExecuteTemplate(f, tmplName, types); err != nil { + defer func() { + closeErr := f.Close() + if err == nil { + err = closeErr + } else if closeErr != nil { + err = fmt.Errorf("close error: %v, original error: %w", closeErr, err) + } + }() + + if err = ptrTmpl.ExecuteTemplate(f, tmplName, types); err != nil { return fmt.Errorf("failed to generate %s file, %v", filename, err) }