Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

net/http: Export request errors #18596

Closed
stevenosborne-wf opened this issue Jan 10, 2017 · 4 comments
Closed

net/http: Export request errors #18596

stevenosborne-wf opened this issue Jan 10, 2017 · 4 comments

Comments

@stevenosborne-wf
Copy link

tl;dr

From the net/http package, export errTimeout, errRequestCanceled, and errRequestCanceledConn.

Request timeout

When making an http request with a timeout, the http client.Do throws an unexported errTimeout. This makes parsing the error problematic. For example:

package main

import (
        "context"
        "fmt"
        "net/http"
        "time"
)

func main() {
        client := http.DefaultClient
        request, _ := http.NewRequest("GET", "https://google.com", nil)
        ctx, _ := context.WithTimeout(context.Background(), 1*time.Millisecond)
        request = request.WithContext(ctx)
        if response, err := client.Do(request); err != nil {
                // Untyped error. Have to scrape error message to find out if it's a
                // timeout.
                fmt.Println(err)
        } else {
                fmt.Println(response.StatusCode)
        }
}

It would be safer to export this error. For example:

package main

import (
        "context"
        "fmt"
        "net/http"
        "time"
)

func main() {
        client := http.DefaultClient
        request, _ := http.NewRequest("GET", "https://google.com", nil)
        ctx, _ := context.WithTimeout(context.Background(), 1*time.Millisecond)
        request = request.WithContext(ctx)
        if response, err := client.Do(request); err != nil {
                // Untyped error. Have to scrape error message to find out if it's a
                // timeout.
                if err == http.ErrTimeout {
                        // Retry request with a back off.
                }
        } else {
                fmt.Println(response.StatusCode)
        }
}
@davecheney
Copy link
Contributor

davecheney commented Jan 10, 2017

Assert if the error implements Timeout() and use that.

if err, ok := err.(net.Error); ok {
      if err.Timeout() { 
            // whatever
      }
}

@bradfitz
Copy link
Contributor

Dup of #15935, #14203, #13667

@stevenosborne-wf
Copy link
Author

@bradfitz I did a quick search and couldn't find a similar issue. Thanks for pointing those out.

@stevenosborne-wf
Copy link
Author

@davecheney Thanks

Sign up for free to subscribe to this conversation on GitHub. Already have an account? Sign in.
Projects
None yet
Development

No branches or pull requests

4 participants