use serde::{Deserialize, Serialize};
use serde_json::Value;
use std::fmt;
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
pub struct Error {
pub code: i32,
pub message: String,
#[serde(skip_serializing_if = "Option::is_none")]
pub data: Option<Value>,
}
impl Error {
pub fn new(code: i32, message: impl Into<String>) -> Self {
Self {
code,
message: message.into(),
data: None,
}
}
pub fn with_data(mut self, data: impl Serialize) -> Self {
self.data = serde_json::to_value(data).ok();
self
}
pub fn invalid_request(details: impl fmt::Display) -> Self {
Self::new(-32600, format!("Invalid Request: {}", details))
}
pub fn method_not_found(method: &str) -> Self {
Self::new(-32601, format!("Method not found: {}", method))
}
pub fn invalid_params(details: impl fmt::Display) -> Self {
Self::new(-32602, format!("Invalid params: {}", details))
}
pub fn internal_error(details: impl fmt::Display) -> Self {
Self::new(-32603, format!("Internal error: {}", details))
}
pub fn parse_error(details: impl fmt::Display) -> Self {
Self::new(-32700, format!("Parse error: {}", details))
}
}
impl fmt::Display for Error {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(f, "jsonrpce::Error {}: {}", self.code, self.message)
}
}
impl std::error::Error for Error {}
impl From<String> for Error {
fn from(s: String) -> Self {
Error::new(-32000, s)
}
}
impl From<&str> for Error {
fn from(s: &str) -> Self {
Error::new(-32000, s)
}
}