use alux_jsonrpc::RpcErrorAlg;
use core::error::Error;
use core::fmt::{self, Display};
use derive_new::new as New;
use serde::Serialize;
pub const PARSE_ERROR: i32 = -32700;
pub const INVALID_REQUEST: i32 = -32600;
pub const METHOD_NOT_FOUND: i32 = -32601;
pub const INVALID_PARAMS: i32 = -32602;
pub const INTERNAL_ERROR: i32 = -32603;
#[derive(Debug, Clone, PartialEq, Eq, Serialize, New)]
pub struct RpcError {
pub code: i32,
#[new(into)]
pub message: String,
}
impl RpcError {
pub fn denoted<Failure>(failure: &Failure) -> Self
where
Failure: RpcErrorAlg,
{
Self { code: failure.rpc_code(), message: failure.rpc_message() }
}
pub fn parse_error() -> Self {
Self::new(PARSE_ERROR, "invalid JSON")
}
pub fn invalid_request() -> Self {
Self::new(INVALID_REQUEST, "invalid request")
}
pub fn method_not_found(method: &str) -> Self {
Self::new(METHOD_NOT_FOUND, format!("method `{method}` not found"))
}
}
impl Display for RpcError {
fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(formatter, "{} ({})", self.message, self.code)
}
}
impl Error for RpcError {}
impl RpcErrorAlg for RpcError {
fn rpc_code(&self) -> i32 {
self.code
}
fn rpc_message(&self) -> String {
self.message.clone()
}
}