-2

Error handling is not possible when I write a method that returns an error with defer in one-liner. It will be warned by IDE linter etc.

I write the following code to avoid it.

package main

import (
    "io/ioutil"
    "log"
    "net/http"
)

func main() {
    req, _ := http.NewRequest("GET", "https://example.com", nil)
    cli := &http.Client{}
    res, _ := cli.Do(req)

    defer func() {
        _ = res.Body.Close() // catch the error
    }()

    b, _ := ioutil.ReadAll(res.Body)
    log.Println(string(b))
}

Jonathan Hall
  • 75,165
  • 16
  • 143
  • 189
junpayment
  • 137
  • 2
  • 9
  • 4
    And what is your actual question? Note that there is not much you can do about request Close returning an error. – Volker Nov 05 '19 at 06:11
  • Thanks for reply. I just want to know how everyone writes when writing a defer with a method returns a error. Because some linter and IDE warn unhandled error. – junpayment Nov 06 '19 at 10:36

1 Answers1

0

The issue here is not the defer, actually its the fact that u are using res.Body without checking for whether res.Body == nil

So the part here is missing is the error handling when cli.Do(req) returns an error and nil for res.

You can still do the same differ by adding in a check for the res being nil. Or you can stop early when cli.Do(req) returns an error

Here is an example https://play.golang.org/p/pnETOjhNCKs

Ravi Chandak
  • 113
  • 1
  • 9
  • I wrote the code as an example, so I skipped some error handling. – junpayment Nov 05 '19 at 07:22
  • Is this an additional issue? is this a different issue checking `res.Body` from handling error with defer? – junpayment Nov 05 '19 at 07:30
  • Handling error using defer is not an issue. Accessing `.Body` from a nil is an issue – Ravi Chandak Nov 05 '19 at 07:33
  • I just want to know how everyone writes when writing a defer with a method returns a error. Because some linter and IDE warn unhandled error. – junpayment Nov 06 '19 at 08:03
  • Warning for unhandled error will be regardless of whether you put it in a defer or not. This warning is just purely based on the fact that the error is not correctly handled. – Ravi Chandak Nov 06 '19 at 09:35