Catalogue
Addressing defer Warnings from Golang errcheck

Addressing defer Warnings from Golang errcheck

🌐 日本語で読む

Overview

When you write code like the following and run errcheck, it flags defer f.Close().

1
2
3
4
5
6
7
8
9
10
func hoge() error {
...
f, err := os.Open(fpath)
if err != nil {
return err
}

defer f.Close()
...
}

The warning says that f.Close() returns an error, and that error return value is not being checked.

Solution

To work around this, you can fix it as follows.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
func hoge() error {
...
f, err := os.Open(fpath)
if err != nil {
return err
}

defer func() {
err = f.Close()
if err != nil {
log.Fatalln(err)
}
}()
...
}

However, in the case above, a panic occurs when an error happens.

If you use log.Println instead, the error does get logged, but you cannot handle subsequent processing based on that error.

So I tried fixing it further as shown below.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
func hoge() (err error) {
...
f, err := os.Open(filepath.Clean(fpath))
if err != nil {
return err
}

defer func() {
if er := f.Close(); er != nil {
err = er
}
}()
...
}

With the following steps, you can return the error from f.Close() as the return value of hoge().

  • Specify a named return value err error in the return values of the hoge() function
  • Store the error returned by f.Close() into err inside the deferred func(){}

Go Playground

References

This topic had already been discussed quite a while ago.

ignore defer calls #55

Addressing defer Warnings from Golang errcheck

https://kenzo0107.github.io/en/2019/12/09/golang-errcheck-defer/

Author

Kenzo Tanaka

Posted on

2019-12-09

Licensed under