//! JSON-RPC failures and conversions from local errors. use serde_json::Value; /// An SDK operation that can fail. pub type Result = std::result::Result; /// A JSON-RPC failure. #[derive(Debug, Clone, serde::Serialize, serde::Deserialize)] pub struct Error { /// The JSON-RPC error code. pub code: i64, /// The diagnostic message. pub message: String, #[serde(skip_serializing_if = "Option::is_none")] /// Optional structured error details. pub data: Option, } impl Error { /// Build the object-params diagnostic used by calls and generated dispatch. #[doc(hidden)] pub fn params_not_object(params: &Value) -> Self { let kind = match params { Value::String(_) => "a string", Value::Array(_) => "an array", Value::Number(_) => "a number", Value::Null => "null", Value::Bool(_) => "a boolean", Value::Object(_) => "an object", }; Self::new( -32602, format!( "params must be a JSON object, got {kind}. Send the object itself, not a JSON-encoded string." ), ) } /// Construct an error without structured details. pub fn new(code: i64, message: impl Into) -> Self { Self { code, message: message.into(), data: None, } } } impl std::fmt::Display for Error { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { f.write_str(&self.message) } } impl std::error::Error for Error {} impl From for Error { fn from(e: std::io::Error) -> Self { Self::new(-32603, e.to_string()) } } impl From for Error { fn from(e: serde_json::Error) -> Self { Self::new(-32603, e.to_string()) } }