Skip to content

Commit

Permalink
Convert non-200 http responses into errors (#254)
Browse files Browse the repository at this point in the history
* fix: use error_for_status in Reqwest transport

* fix: capture non-200 responses in hyper

* nit: comment fix

* fix: query status before moving resp

* fix: use utf8 lossy in error
  • Loading branch information
prestwich authored Mar 8, 2024
1 parent 9430040 commit d66e9b8
Show file tree
Hide file tree
Showing 2 changed files with 16 additions and 1 deletion.
14 changes: 13 additions & 1 deletion crates/transport-http/src/hyper.rs
Original file line number Diff line number Diff line change
Expand Up @@ -30,11 +30,23 @@ where

let resp = this.client.request(req).await.map_err(TransportErrorKind::custom)?;

// unpack json from the response body
let status = resp.status();

// unpack data from the response body. We do this regardless of
// the status code, as we want to return the error in the body if
// there is one.
let body = hyper::body::to_bytes(resp.into_body())
.await
.map_err(TransportErrorKind::custom)?;

if status != hyper::StatusCode::OK {
return Err(TransportErrorKind::custom_str(&format!(
r#"HTTP error: {} with body: "{}""#,
status,
String::from_utf8_lossy(body.as_ref())
)));
}

// Deser a Box<RawValue> from the body. If deser fails, return the
// body as a string in the error. If the body is not UTF8, this will
// fail and give the empty string in the error.
Expand Down
3 changes: 3 additions & 0 deletions crates/transport-http/src/reqwest.rs
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
use crate::Http;
use alloy_json_rpc::{RequestPacket, ResponsePacket};
use alloy_transport::{TransportError, TransportErrorKind, TransportFut};
use reqwest::Response;
use std::task;
use tower::Service;

Expand All @@ -15,7 +16,9 @@ impl Http<reqwest::Client> {
.json(&req)
.send()
.await
.and_then(Response::error_for_status)
.map_err(TransportErrorKind::custom)?;

let body = resp.bytes().await.map_err(TransportErrorKind::custom)?;

serde_json::from_slice(&body)
Expand Down

0 comments on commit d66e9b8

Please sign in to comment.