英文:
(*testing.common).Errorf does not support error-wrapping directive %w
问题
我正在克隆一个私有的Go项目。
在代码编辑器和运行golangci-lint时,遇到了以下错误。
示例代码如下:
func TestAService(t *testing.T) {
...
err := service.AService()
if err != nil {
t.Errorf("执行测试用例时出错:%w", err)
}
}
这个Go项目在其他笔记本电脑上正常运行,但我使用的这台笔记本电脑出现了这个错误。
两台笔记本电脑使用的Go版本都是:go 1.17
英文:
I was cloning a private go project.
And got below error on the code editor and when running golangci-lint.
golangci-lint screenshot error
The sample code is this:
func TestAService(t *testing.T) {
...
err := service.AService()
if err != nil {
t.Errorf("Error on executing the test cases %w", err)
}
}
The go project runs fine on other laptop, but the one I use it has this error.
The go version used by both laptop are: go 1.17
答案1
得分: 6
你发布的截图并不是错误,而是你的IDE关于代码潜在问题的警告。
但是testing.T.Errorf
不支持%w
(它与fmt.Sprintf
的功能和接受方式相同),所以这些警告是正确的。
这些消息不会阻止你的代码构建和运行,但是在出现错误时,字符串的格式可能会出错。
如果你运行代码,并且出现错误,你会得到类似下面的输出(%!w
之后的部分取决于你具体的错误值)。
在执行测试用例时出错 %!w(*errors.errorString=&{some error})
你收到的具体警告可能是新的<sup>1</sup>,但我不认为这个错误代码在任何go版本中都能正常工作。当然,由于大多数测试错误通常不会被看到(因为测试通过),这个缺陷可能一直是不可见的。
修复方法是将%w
(包装错误)替换为%v
(以默认方式格式化对象,对于错误来说将使用其字符串形式)。
<sup>1</sup> 你看到的lint消息来自于"go tool vet",由此更改列表创建,该更改列表于2021年5月提交。可能在你的其他机器上,你正在使用此工具的早期版本进行lint。
英文:
The screenshots you post aren't errors, they're warnings from your IDE about potential problems in your code.
But testing.T.Errorf
does not support %w
(it's the same as fmt.Sprintf
in what it does and doesn't accept), so the warnings are correct.
The messages do not stop your code from building and running, but in the case of an error, the formatting of the string will be off.
If you run the code, and there's an error, you'll get something like this (the part after %!w
will depend on the exact error value you have).
Error on executing the test cases %!w(*errors.errorString=&{some error})
The specific warning you're getting might be new<sup>1</sup>, but I don't believe this error code would ever have worked satisfactorily in any version of go. Of course, since most test errors are most often not seen (because tests pass), it may be that this defect has remained invisible.
The fix is to replace %w
(wrap error) with %v
(format object in the default way, which for an error will be to use its string form).
<sup>1</sup> The lint message you're seeing is from "go tool vet", created by this changelist which was committed in May 2021. It's possible on your other machine, you are linting using an earlier version of this tool.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论