Skip to content

Commit

Permalink
Merge pull request #498 from amazonlinux/apiclient-bad-response-status
Browse files Browse the repository at this point in the history
apiclient: error on non-2xx response
  • Loading branch information
etungsten authored Nov 11, 2019
2 parents e1d4edc + ea15701 commit 912b2ff
Showing 1 changed file with 17 additions and 2 deletions.
19 changes: 17 additions & 2 deletions workspaces/api/apiclient/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -18,7 +18,7 @@ use futures::Future;
use hyper::rt::Stream;
use hyper::{header, Body, Client, Request};
use hyperlocal::{UnixConnector, Uri};
use snafu::ResultExt;
use snafu::{ensure, ResultExt};
use std::path::Path;
use tokio::runtime::Runtime;

Expand All @@ -38,6 +38,12 @@ mod error {
#[snafu(display("Failed to send request: {}", source))]
RequestSend { source: hyper::Error },

#[snafu(display("Status {} {} when requesting {}", code.as_u16(), code.as_str(), uri))]
ResponseStatus {
code: http::StatusCode,
uri: http::uri::Uri,
},

#[snafu(display("Failed to read body of response: {}", source))]
ResponseBodyRead { source: hyper::Error },

Expand Down Expand Up @@ -87,7 +93,7 @@ where

let request = Request::builder()
.method(method.as_ref())
.uri(uri)
.uri(&uri)
.header(header::CONTENT_TYPE, "application/json")
.body(Body::from(request_data))
.context(error::RequestSetup)?;
Expand All @@ -102,6 +108,15 @@ where
.block_on(client.request(request).map(|res| res.into_parts()))
.context(error::RequestSend)?;

// Error if the response status is in not in the 2xx range.
ensure!(
head.status.is_success(),
error::ResponseStatus {
code: head.status,
uri
}
);

// Wait on the second future (the streaming body) and concatenate all the pieces together so we
// have a single response body. We make sure each piece is a string, as we go; we assume that
// we're not handling binary data.
Expand Down

0 comments on commit 912b2ff

Please sign in to comment.