rpc: add HTTPError type for HTTP error responses (#22677)

The new error type is returned by client operations contains details of
the response error code and response body.

Co-authored-by: Felix Lange <fjl@twurst.com>
This commit is contained in:
ryanc414
2021-04-21 14:51:30 +01:00
committed by GitHub
parent 67da83aca5
commit 9357280fce
4 changed files with 81 additions and 23 deletions

View File

@ -123,3 +123,42 @@ func TestHTTPRespBodyUnlimited(t *testing.T) {
t.Fatalf("response has wrong length %d, want %d", len(r), respLength)
}
}
// Tests that an HTTP error results in an HTTPError instance
// being returned with the expected attributes.
func TestHTTPErrorResponse(t *testing.T) {
ts := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
http.Error(w, "error has occurred!", http.StatusTeapot)
}))
defer ts.Close()
c, err := DialHTTP(ts.URL)
if err != nil {
t.Fatal(err)
}
var r string
err = c.Call(&r, "test_method")
if err == nil {
t.Fatal("error was expected")
}
httpErr, ok := err.(HTTPError)
if !ok {
t.Fatalf("unexpected error type %T", err)
}
if httpErr.StatusCode != http.StatusTeapot {
t.Error("unexpected status code", httpErr.StatusCode)
}
if httpErr.Status != "418 I'm a teapot" {
t.Error("unexpected status text", httpErr.Status)
}
if body := string(httpErr.Body); body != "error has occurred!\n" {
t.Error("unexpected body", body)
}
if errMsg := httpErr.Error(); errMsg != "418 I'm a teapot: error has occurred!\n" {
t.Error("unexpected error message", errMsg)
}
}