Skip to content

Commit b4e7a38

Browse files
MichaelUrmanpolyfloyd
authored andcommitted
Permit switch err with case nil or default
1 parent 6372a84 commit b4e7a38

File tree

2 files changed

+31
-0
lines changed

2 files changed

+31
-0
lines changed

errorlint/lint.go

+21
Original file line numberDiff line numberDiff line change
@@ -189,6 +189,27 @@ func LintErrorComparisons(fset *token.FileSet, info *TypesInfoExt) []Lint {
189189
continue
190190
}
191191

192+
hasErrorCase := false
193+
for _, caseBlock := range switchStmt.Body.List {
194+
caseClause, ok := caseBlock.(*ast.CaseClause)
195+
if !ok {
196+
continue
197+
}
198+
for _, clause := range caseClause.List {
199+
switch clause := clause.(type) {
200+
case nil:
201+
continue // default label is safe
202+
case *ast.Ident:
203+
if clause.Name != "nil" {
204+
hasErrorCase = true
205+
}
206+
}
207+
}
208+
}
209+
if !hasErrorCase {
210+
continue
211+
}
212+
192213
lints = append(lints, Lint{
193214
Message: "switch on an error will fail on wrapped errors. Use errors.Is to check for specific errors",
194215
Pos: switchStmt.Pos(),

errorlint/testdata/src/errorsis/errorsis.go

+10
Original file line numberDiff line numberDiff line change
@@ -82,6 +82,16 @@ func CompareSwitch() {
8282
}
8383
}
8484

85+
func CompareSwitchNilDefault() {
86+
err := doThing()
87+
switch err {
88+
case nil:
89+
fmt.Println("success")
90+
default:
91+
fmt.Println("failure")
92+
}
93+
}
94+
8595
func CompareSwitchInline() {
8696
switch doThing() { // want `switch on an error will fail on wrapped errors. Use errors.Is to check for specific errors`
8797
case ErrFoo:

0 commit comments

Comments
 (0)