hyprstream_rpc/capnp/error.rs
1//! Error handling extensions for Cap'n Proto operations.
2
3use thiserror::Error;
4
5/// RPC-specific error types.
6#[derive(Debug, Error)]
7pub enum RpcError {
8 /// Cap'n Proto serialization/deserialization error.
9 #[error("Serialization error: {0}")]
10 Serialization(String),
11
12 /// Transport error (ZMQ, network, etc.).
13 #[error("Transport error: {0}")]
14 Transport(String),
15
16 /// Service returned an error response.
17 #[error("Service error: {0}")]
18 Service(String),
19
20 /// Unexpected response type from service.
21 #[error("Unexpected response type")]
22 UnexpectedResponse,
23
24 /// Service is unavailable.
25 #[error("Service unavailable")]
26 Unavailable,
27}
28
29impl RpcError {
30 /// Create a transport error.
31 pub fn transport<S: Into<String>>(msg: S) -> Self {
32 Self::Transport(msg.into())
33 }
34
35 /// Create a serialization error.
36 pub fn serialization<S: Into<String>>(msg: S) -> Self {
37 Self::Serialization(msg.into())
38 }
39
40 /// Create a service error.
41 pub fn service<S: Into<String>>(msg: S) -> Self {
42 Self::Service(msg.into())
43 }
44}
45
46/// Extension trait for adding RPC error context to Results.
47///
48/// Simplifies the common pattern of mapping errors to RPC errors.
49///
50/// # Example
51///
52/// ```ignore
53/// use hyprstream_rpc::capnp::CapnpResultExt;
54///
55/// // Instead of:
56/// let value = reader.get_field()
57/// .map_err(|e| RpcError::serialization(e.to_string()))?
58/// .to_str()
59/// .map_err(|e| RpcError::serialization(e.to_string()))?;
60///
61/// // Write:
62/// let value = reader.get_field().rpc_err()?.to_str().rpc_err()?;
63/// ```
64pub trait CapnpResultExt<T> {
65 /// Convert error to RpcError::Serialization.
66 fn rpc_err(self) -> Result<T, RpcError>;
67
68 /// Convert error to RpcError::Transport.
69 fn transport_err(self) -> Result<T, RpcError>;
70}
71
72impl<T, E: std::fmt::Display> CapnpResultExt<T> for Result<T, E> {
73 fn rpc_err(self) -> Result<T, RpcError> {
74 self.map_err(|e| RpcError::serialization(e.to_string()))
75 }
76
77 fn transport_err(self) -> Result<T, RpcError> {
78 self.map_err(|e| RpcError::transport(e.to_string()))
79 }
80}