如何检测未使用的错误值

huangapple go评论90阅读模式
英文:

How to detect error values that are never used

问题

我正在寻找一种方法来查找不处理第一个错误的错误"handling"的出现:

示例:

func handler() {
   var myErr error

   myErr = doSomething() //请提醒我这个

   myErr = doSomethingElse()

   if myErr != nil {
      return
   }

}

func doSomething() error {
	return errors.New("an example error")
}

func doSomethingElse() error {
	return errors.New("an example error")
}

我希望在第一次调用svc.DoSomething()后警告我没有使用错误,因为它被有效地覆盖和忽略了。

我尝试在Goland 2021.3中启用所有代码检查,并尝试了staticcheck,并搜索了现有的代码检查工具。

我相信它应该在第一次调用svc.DoSomething()后显示SA4006,这在VSCode中可以正常工作。

英文:

I'm looking for a way to to find occurrences of this error "handling" that doesn't do anything with the first error:

example:

func handler() {
   var myErr error

   myErr = doSomething() //Warn me about this please

   myErr = doSomethingElse()

   if myErr != nil {
      return
   }

}

func doSomething() error {
	return errors.New("an example error")
}

func doSomethingElse() error {
	return errors.New("an example error")
}

I would like to be warned that I haven't used the error after the first call to svc.DoSomething() because its effectively overwritten and ignored.

I have tried enabling all code inspections in goland 2021.3 and have tried staticcheck and have searched for an existing linter.

I believe it should show SA4006 after the first call to svc.DoSomething() which works fine in VSCode.

答案1

得分: 2

我建议使用ineffassign linter:https://github.com/gordonklaus/ineffassign

它可以作为一个独立的工具使用,也可以通过golangci-lint使用:https://golangci-lint.run/usage/linters/

它不仅会检查错误,还会检查所有无用的赋值(即后续没有使用的赋值),就像你的例子中一样。

英文:

I'd suggest the ineffassign linter: https://github.com/gordonklaus/ineffassign

It can be used as a standalone tool or via golangci-lint: https://golangci-lint.run/usage/linters/

It's not gonna check only for error, but for all useless assignments (ie that aren't used latter on) like in your example.

答案2

得分: -1

VSCode做了同样的事情。

如何检测未使用的错误值

在我使用这个变量之后:

如何检测未使用的错误值

文档:https://pkg.go.dev/golang.org/x/tools/internal/typesinternal#UnusedVar

诊断工具:https://github.com/golang/vscode-go/wiki/tools#diagnostics

英文:

VSCode does the same thing.

如何检测未使用的错误值

After I use this variable:

如何检测未使用的错误值

Doc: https://pkg.go.dev/golang.org/x/tools/internal/typesinternal#UnusedVar

Diagnostic Tools: https://github.com/golang/vscode-go/wiki/tools#diagnostics

huangapple
  • 本文由 发表于 2023年6月14日 18:51:09
  • 转载请务必保留本文链接:https://go.coder-hub.com/76472727.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定