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

apiclient: error on non-2xx response #498

Merged
merged 1 commit into from
Nov 11, 2019
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
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