alux_jsonrpc_direct/
error.rs1use alux_jsonrpc::RpcErrorAlg;
2use core::error::Error;
3use core::fmt::{self, Display};
4use derive_new::new as New;
5use serde::Serialize;
6
7pub const PARSE_ERROR: i32 = -32700;
9pub const INVALID_REQUEST: i32 = -32600;
11pub const METHOD_NOT_FOUND: i32 = -32601;
13pub const INVALID_PARAMS: i32 = -32602;
15pub const INTERNAL_ERROR: i32 = -32603;
17
18#[derive(Debug, Clone, PartialEq, Eq, Serialize, New)]
20pub struct RpcError {
21 pub code: i32,
23 #[new(into)]
25 pub message: String,
26}
27
28impl RpcError {
29 pub fn denoted<Failure>(failure: &Failure) -> Self
31 where
32 Failure: RpcErrorAlg,
33 {
34 Self { code: failure.rpc_code(), message: failure.rpc_message() }
35 }
36
37 pub fn parse_error() -> Self {
39 Self::new(PARSE_ERROR, "invalid JSON")
40 }
41
42 pub fn invalid_request() -> Self {
44 Self::new(INVALID_REQUEST, "invalid request")
45 }
46
47 pub fn method_not_found(method: &str) -> Self {
49 Self::new(METHOD_NOT_FOUND, format!("method `{method}` not found"))
50 }
51}
52
53impl Display for RpcError {
54 fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
55 write!(formatter, "{} ({})", self.message, self.code)
56 }
57}
58
59impl Error for RpcError {}
60
61impl RpcErrorAlg for RpcError {
63 fn rpc_code(&self) -> i32 {
64 self.code
65 }
66
67 fn rpc_message(&self) -> String {
68 self.message.clone()
69 }
70}