Skip to content

Commit

Permalink
Handle error for defered file close call (#314)
Browse files Browse the repository at this point in the history
Handle error for defer close call
  • Loading branch information
skotambkar authored Jul 29, 2021
1 parent e488a70 commit 5c681d5
Showing 1 changed file with 11 additions and 3 deletions.
14 changes: 11 additions & 3 deletions ptr/generate.go
Original file line number Diff line number Diff line change
Expand Up @@ -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)
}

Expand Down

0 comments on commit 5c681d5

Please sign in to comment.