Missing error check¶
ID: go/missing-error-checkKind: problemSecurity severity: Severity: warningPrecision: highTags: - quality - reliability - error-handling - external/cwe/cwe-252Query suites: - go-security-and-quality.qls
Click to see the query in the CodeQL repository
When a function call returns two values, a pointer and a (subtype of) error, it is conventional to assume that the pointer might be nil until either the pointer or error value has been checked.
If the pointer is dereferenced without a check, an unexpected nil pointer dereference panic may occur.
Recommendation¶
Ensure that the returned pointer is either directly checked against nil, or the error value is checked before using the returned pointer.
Example¶
In the example below,user dereferencesptr without checking eitherptr orerr. This might lead to a panic.
packagemainimport("fmt""os")funcuser(inputstring){ptr,err:=os.Open(input)// BAD: ptr is dereferenced before either it or `err` has been checked.fmt.Printf("Opened %v\n",*ptr)iferr!=nil{fmt.Printf("Bad input: %s\n",input)}}
The corrected version ofuser checkserr before usingptr.
packagemainimport("fmt""os")funcuser(inputstring){ptr,err:=os.Open(input)iferr!=nil{fmt.Printf("Bad input: %s\n",input)return}// GOOD: `err` has been checked before `ptr` is usedfmt.Printf("Result was %v\n",*ptr)}
References¶
The Go Blog:Error handling and Go.
Common Weakness Enumeration:CWE-252.