Movatterモバイル変換


[0]ホーム

URL:


CodeQL documentation
CodeQL resources

Wrapped error is always nil

ID: go/unexpected-nil-valueKind: problemSecurity severity: Severity: warningPrecision: highTags:   - quality   - reliability   - error-handlingQuery suites:   - go-security-and-quality.qls

Click to see the query in the CodeQL repository

Thepkg.errors package provides theerrors.Wrap function for annotating an error with a stack trace. When passednil, this function returnsnil. When the first parameter toerrors.Wrap isalwaysnil, the function call has no effect and likely indicates a programming mistake. A common example of this is when anerrors.Wrap(err,"message") call is copied from an earlier error-handling block in the same function and used in a subsequent error-handling block that does not checkerr in its guard. In this case the return of anil value to the caller indicates by convention that the operation succeeded, and so the failure is masked.

Recommendation

Usually anerr value is being referenced outside its intended scope. The problem can be fixed by removing that reference, for example by changing a call of the formerrors.Wrap(err,"message") toerrors.New("message").

Example

The example below shows an example where theerr value returned from the call tof1 is reused in a later call, when it is known to benil:

packagemainimport("github.com/pkg/errors")funcf1(inputstring)error{ifinput=="1"{returnerrors.Errorf("error in f1")}returnnil}funcf2(inputstring)(bool,error){ifinput=="2"{returnfalse,errors.Errorf("error in f2")}returntrue,nil}functest1(inputstring)error{err:=f1(input)iferr!=nil{returnerrors.Wrap(err,"input is the first non-negative integer")}ifok2,_:=f2(input);!ok2{returnerrors.Wrap(err,"input is the second non-negative integer")}returnnil}

One way of fixing this is to create a new error value witherrors.New:

packagemainimport("github.com/pkg/errors")funcf1(inputstring)error{ifinput=="1"{returnerrors.Errorf("error in f1")}returnnil}funcf2(inputstring)(bool,error){ifinput=="2"{returnfalse,errors.Errorf("error in f2")}returntrue,nil}functest1(inputstring)error{err:=f1(input)iferr!=nil{returnerrors.Wrap(err,"input is the first non-negative integer")}ifok2,_:=f2(input);!ok2{returnerrors.New("input is the second non-negative integer")}returnnil}

References


[8]ページ先頭

©2009-2025 Movatter.jp