Skip to content

Commit b2f16ad

Browse files
committed
Parse RPC errors as JSON content
Bitcoin Core's JSON RPC server returns errors as HTTP error responses with JSON content in the body. Parse this content as JSON to give a more meaningful error. Otherwise, "binary" is given because the content contains ASCII control characters.
1 parent 61648fc commit b2f16ad

File tree

1 file changed

+16
-4
lines changed
  • lightning-block-sync/src

1 file changed

+16
-4
lines changed

lightning-block-sync/src/rpc.rs

Lines changed: 16 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -2,7 +2,7 @@
22
//! endpoint.
33
44
use crate::{BlockHeaderData, BlockSource, AsyncBlockSourceResult};
5-
use crate::http::{HttpClient, HttpEndpoint, JsonResponse};
5+
use crate::http::{HttpClient, HttpEndpoint, HttpError, JsonResponse};
66

77
use bitcoin::blockdata::block::Block;
88
use bitcoin::hash_types::BlockHash;
@@ -47,8 +47,20 @@ impl RpcClient {
4747
"id": &self.id.fetch_add(1, Ordering::AcqRel).to_string()
4848
});
4949

50-
let mut response = self.client.post::<JsonResponse>(&uri, &host, &self.basic_auth, content)
51-
.await?.0;
50+
let mut response = match self.client.post::<JsonResponse>(&uri, &host, &self.basic_auth, content).await {
51+
Ok(JsonResponse(response)) => response,
52+
Err(e) if e.kind() == std::io::ErrorKind::Other => {
53+
match e.get_ref().unwrap().downcast_ref::<HttpError>() {
54+
Some(http_error) => match JsonResponse::try_from(http_error.contents.clone()) {
55+
Ok(JsonResponse(response)) => response,
56+
Err(_) => Err(e)?,
57+
},
58+
None => Err(e)?,
59+
}
60+
},
61+
Err(e) => Err(e)?,
62+
};
63+
5264
if !response.is_object() {
5365
return Err(std::io::Error::new(std::io::ErrorKind::InvalidData, "expected JSON object"));
5466
}
@@ -143,7 +155,7 @@ mod tests {
143155
let response = serde_json::json!({
144156
"error": { "code": -8, "message": "invalid parameter" },
145157
});
146-
let server = HttpServer::responding_with_ok(MessageBody::Content(response));
158+
let server = HttpServer::responding_with_server_error(response);
147159
let mut client = RpcClient::new(CREDENTIALS, server.endpoint()).unwrap();
148160

149161
let invalid_block_hash = serde_json::json!("foo");

0 commit comments

Comments
 (0)