英文:
Error return value of `app.errorLog.Output` is not checked
问题
我对golang还不太熟悉,对不起,我有一个问题。
我有以下函数:
func (app *application) serverError(w http.ResponseWriter, err error) {
trace := fmt.Sprintf("%s\n%s", err.Error(), debug.Stack())
app.errorLog.Output(2, trace)
http.Error(w, http.StatusText(http.StatusInternalServerError), http.StatusInternalServerError)
}
我正在使用golangci-lint linter,当我启动linter时,它返回以下错误:
cmd/web/helpers.go:15:22: `app.errorLog.Output` 的错误返回值未被检查 (errcheck)
app.errorLog.Output(2, trace)
^
我该如何修复这个问题?
英文:
I'm pretty new to golang so sorry for my question.
I have the following function:
func (app *application) serverError(w http.ResponseWriter, err error) {
trace := fmt.Sprintf("%s\n%s", err.Error(), debug.Stack())
app.errorLog.Output(2, trace)
http.Error(w, http.StatusText(http.StatusInternalServerError), http.StatusInternalServerError)
}
I'm using golangci-lint linter, and when I launch the linter, it returns the following error:
cmd/web/helpers.go:15:22: Error return value of `app.errorLog.Output` is not checked (errcheck)
app.errorLog.Output(2, trace)
^
How can I fix that?
答案1
得分: 1
在Go语言中,一种常见的模式是定义一个函数,该函数返回两个值,第一个是期望的结果,第二个是error
类型。
通常情况下,如果由于某些错误e
而无法提供一个值,函数会返回nil, e
或<类型的零值>, e
。
然而,并不一定只有一个期望的结果值,有时可能会有零个或多个期望的结果值。基本规则是:如果函数的最后一个返回值是error
类型,并且文档没有其他说明,那么在继续之前,始终要检查该返回值。
因此,当你在返回签名中看到这种模式时,不应该使用忽略返回或将其赋值给_
来丢弃最后一个结果,而应该检查该值,确保它不为nil
后再继续执行。
第一个反模式是linter(代码检查工具)正在警告你的内容。你可以这样检查错误参数(我假设这里没有任何“期望的结果”值):
if err := app.errorLog.Output(2, trace); err != nil {
// ... 在这里处理错误或者 panic(err)
}
这样可以满足linter的要求,并使你的代码更加健壮!
英文:
In go, a common pattern is to have a function that returns two values, the first of which is the desired result, and the second of which is type error
.
Typically, if an implementation cannot provide a value because of some error e
, it will return nil, e
or return <zero value for type>, e
.
It doesn't just have to be one such desired result value, however - sometimes there will be zero or more than one desired result values. Basic rule: if the last return value of a function is error
typed, and the docs don't say otherwise, always check that last return value.
So, when you see such a pattern in a return signature - you should not discard the last result with a ignored return or an assign to '_', but should check that value to make sure it is non-nil before continuing.
The first of those anti-patterns is what the linter is warning you about. You can check the error argument thusly (I'm assuming that there are zero "desired result" values here):
if err := app.errorLog.Output(2, trace); err != nil {
// ... do something to handle error here or panic(err)
}
This will satisfy the linter and make your code more robust!
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论