Skip to content

Commit 0dc7e50

Browse files
committed
cln-plugin: include the full error chain when given a context
Changelog-None
1 parent 066056d commit 0dc7e50

1 file changed

Lines changed: 29 additions & 8 deletions

File tree

plugins/src/lib.rs

Lines changed: 29 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -2,8 +2,8 @@ use crate::codec::{JsonCodec, JsonRpcCodec};
22
pub use anyhow::anyhow;
33
use anyhow::{Context, Result};
44
use futures::sink::SinkExt;
5-
use serde::de::DeserializeOwned;
65
use serde::Serialize;
6+
use serde::de::DeserializeOwned;
77
use tokio::io::{AsyncReadExt, AsyncWriteExt};
88
extern crate log;
99
use log::trace;
@@ -973,7 +973,7 @@ where
973973
.send(json!({
974974
"jsonrpc": "2.0",
975975
"id": id,
976-
"error": parse_error(e.to_string()),
976+
"error": parse_error(&e),
977977
}))
978978
.await
979979
.context("returning custom error"),
@@ -1112,14 +1112,20 @@ struct RpcError {
11121112
pub message: String,
11131113
pub data: Option<serde_json::Value>,
11141114
}
1115-
fn parse_error(error: String) -> RpcError {
1116-
match serde_json::from_str::<RpcError>(&error) {
1117-
Ok(o) => o,
1118-
Err(_) => RpcError {
1115+
fn parse_error(error: &anyhow::Error) -> RpcError {
1116+
if let Ok(o) = serde_json::from_str::<RpcError>(&error.to_string()) {
1117+
o
1118+
} else {
1119+
let message = error
1120+
.chain()
1121+
.map(std::string::ToString::to_string)
1122+
.collect::<Vec<_>>()
1123+
.join(": ");
1124+
RpcError {
11191125
code: Some(-32700),
1120-
message: error,
1126+
message,
11211127
data: None,
1122-
},
1128+
}
11231129
}
11241130
}
11251131

@@ -1133,4 +1139,19 @@ mod test {
11331139
let builder = Builder::new(tokio::io::stdin(), tokio::io::stdout());
11341140
let _ = builder.start(state);
11351141
}
1142+
#[test]
1143+
fn parse_error_includes_full_anyhow_chain() {
1144+
let err = anyhow!("No such file or directory (os error 2)")
1145+
.context("config file missing")
1146+
.context("failed to load config");
1147+
1148+
let rpc_error = parse_error(&err);
1149+
1150+
assert_eq!(rpc_error.code, Some(-32700));
1151+
assert_eq!(
1152+
rpc_error.message,
1153+
"failed to load config: config file missing: No such file or directory (os error 2)"
1154+
);
1155+
assert_eq!(rpc_error.data, None);
1156+
}
11361157
}

0 commit comments

Comments
 (0)