相关文章推荐
好帅的米饭  ·  如何计算Spring ...·  1 年前    · 
叛逆的消防车  ·  image - Convert RGBA ...·  1 年前    · 
温文尔雅的砖头  ·  Specifying a ...·  1 年前    · 
Collectives™ on Stack Overflow

Find centralized, trusted content and collaborate around the technologies you use most.

Learn more about Collectives

Teams

Q&A for work

Connect and share knowledge within a single location that is structured and easy to search.

Learn more about Teams

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?

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!

If there were one non-error return value, and you wanted to ignore it, you'd say if _, err := app.errorLog.Output(2, trace); err != nil { ... – BadZen Jun 21, 2021 at 20:05

Thanks for contributing an answer to Stack Overflow!

  • Please be sure to answer the question. Provide details and share your research!

But avoid

  • Asking for help, clarification, or responding to other answers.
  • Making statements based on opinion; back them up with references or personal experience.

To learn more, see our tips on writing great answers.