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

Example for HTTPResponse error #15598

Merged
merged 1 commit into from
Sep 20, 2021
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
27 changes: 27 additions & 0 deletions sdk/azcore/example_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -8,11 +8,16 @@
package azcore_test

import (
"context"
"encoding/json"
"errors"
"fmt"
"io/ioutil"
"net/http"

"github.com/Azure/azure-sdk-for-go/sdk/azcore"
"github.com/Azure/azure-sdk-for-go/sdk/azcore/log"
"github.com/Azure/azure-sdk-for-go/sdk/azcore/runtime"
)

// false positive by linter
Expand Down Expand Up @@ -58,3 +63,25 @@ func ExampleNullValue() {
// Output:
// {"count":null}
}

func ExampleHTTPResponse() {
pipeline := runtime.NewPipeline(http.DefaultClient)
req, err := runtime.NewRequest(context.Background(), "POST", "https://fakecontainerregisty.azurecr.io/acr/v1/nonexisteng/_tags")
if err != nil {
panic(err)
}
resp, err := pipeline.Do(req)
var httpErr azcore.HTTPResponse
if errors.As(err, &httpErr) {
// Handle Error
if httpErr.RawResponse().StatusCode == http.StatusNotFound {
fmt.Printf("Repository could not be found: %v", httpErr.RawResponse())
} else if httpErr.RawResponse().StatusCode == http.StatusForbidden {
fmt.Printf("You do not have permission to access this repository: %v", httpErr.RawResponse())
} else {
// ...
}
}
// Do something with response
fmt.Println(ioutil.ReadAll(resp.Body))
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Should we check that resp is not nil? Ie, are azcore.HTTPResponse's the only errors that can come back here?

Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

So HTTPResponse is the interface used to get at the underlying *http.Response from an error returned by SDK code due to a failure HTTP status code. In the context of this example, Do() will never return an HTTPResponse error because there's no HTTP status code to predicate success/failure.

}