use std::fmt::Display;
use std::fmt::Formatter;
use serde::Deserialize;
use serde::Serialize;
use serde_json::Value;
use super::constants::BRP_ERROR_ACCESS_ERROR;
use super::constants::BRP_ERROR_CODE_UNKNOWN_COMPONENT_TYPE;
use super::constants::JSON_RPC_ERROR_INTERNAL_ERROR;
use super::constants::JSON_RPC_ERROR_INVALID_PARAMS;
use crate::error::Result;
pub trait BrpToolConfig {
const ADD_TYPE_GUIDE_TO_ERROR: bool = false;
}
pub trait ResultStructBrpExt: Sized {
type Args;
fn from_brp_client_response(response: Self::Args) -> Result<Self>;
}
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct BrpClientError {
pub code: i32,
pub message: String,
pub data: Option<Value>,
}
impl BrpClientError {
pub const fn get_code(&self) -> i32 { self.code }
pub fn get_message(&self) -> &str { &self.message }
pub const fn has_format_error_code(&self) -> bool {
matches!(
self.code,
JSON_RPC_ERROR_INVALID_PARAMS
| JSON_RPC_ERROR_INTERNAL_ERROR
| BRP_ERROR_CODE_UNKNOWN_COMPONENT_TYPE
| BRP_ERROR_ACCESS_ERROR
)
}
}
impl Display for BrpClientError {
fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result { write!(f, "{}", self.message) }
}
#[derive(Debug, Serialize, Deserialize)]
pub(super) struct BrpClientCallJsonResponse {
pub jsonrpc: String,
pub id: u64,
#[serde(skip_serializing_if = "Option::is_none")]
pub result: Option<Value>,
#[serde(skip_serializing_if = "Option::is_none")]
pub error: Option<JsonRpcError>,
}
#[derive(Debug, Serialize, Deserialize)]
pub(super) struct JsonRpcError {
pub code: i32,
pub message: String,
#[serde(skip_serializing_if = "Option::is_none")]
pub data: Option<Value>,
}
#[derive(Debug, Clone, Serialize, Deserialize)]
pub enum ResponseStatus {
Success(Option<Value>),
Error(BrpClientError),
}
#[derive(Debug, Clone, PartialEq, Eq, serde::Serialize, serde::Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum FormatCorrectionStatus {
NotApplicable,
NotAttempted,
Succeeded,
}
#[cfg(test)]
mod tests {
use super::BRP_ERROR_CODE_UNKNOWN_COMPONENT_TYPE;
use super::BrpClientError;
use super::JSON_RPC_ERROR_INVALID_PARAMS;
use crate::brp_tools::JSON_RPC_ERROR_METHOD_NOT_FOUND;
#[test]
fn test_brp_client_error_display() {
let error = BrpClientError {
code: JSON_RPC_ERROR_INVALID_PARAMS,
message: "Invalid params".to_string(),
data: None,
};
assert_eq!(error.to_string(), "Invalid params");
}
#[test]
fn test_brp_client_error_is_format_error() {
let format_error = BrpClientError {
code: JSON_RPC_ERROR_INVALID_PARAMS,
message: "Invalid params".to_string(),
data: None,
};
assert!(format_error.has_format_error_code());
let unknown_component_error = BrpClientError {
code: BRP_ERROR_CODE_UNKNOWN_COMPONENT_TYPE,
message: "Unknown component type".to_string(),
data: None,
};
assert!(unknown_component_error.has_format_error_code());
let non_format_error = BrpClientError {
code: JSON_RPC_ERROR_METHOD_NOT_FOUND,
message: "Method not found".to_string(),
data: None,
};
assert!(!non_format_error.has_format_error_code());
}
}