errcheck: errcheck should not detect "defer" with error
It’s common in go to use defer
with Close()
methods.
file, err := os.Open("/path/to/file")
if err != nil {
return err
}
defer file.Close()
However errcheck detects this as warning.
About this issue
- Original URL
- State: closed
- Created 8 years ago
- Reactions: 14
- Comments: 17 (2 by maintainers)
Yes, please consider providing an option to disable error check in defer calls. It is 100% correct to open a file read-only and defer-Close it. The same goes for closing receiving streams. Many example and library go codes use defer x.Close and we all don’t want to use CloseQuietly() just to shut the the linter up.
it’s just so stupid this linter doesn’t support disabling defer check. Like, just because of this one tiny thing, I have to sit here wasting my time to find the least ugly way to bypass this
This is a duplicate of of #55 and #77 – Check these two issues for why the warnings are appropriate and won’t be removed.
I agree that this has already been covered. Your example in the ticket is a good reason why defer should not be ignored. If
file.Close()
returns an error it could mean that the contents couldn’t be flushed to disk and the file is corrupted, etc. That’s something a program may care about. Henceerrcheck
will warn about this since it’s a detail you potentially missed.I think explicitly checking and ignoring he error by assigning it to blank and leaving a comment as to why it’s not being checked, or adding it to the ignores for checks in the project, is a good way of documenting that you don’t actually care about this for a particular case.
I’m definitely against adding any kind of in-code pragmas for errcheck. Tools fall in and out of favour all the time and I don’t think it’s a good thing to litter code with comments to accommodate them.