weirdnet_service/
error.rs1use serde::{Deserialize, Serialize};
4
5#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, thiserror::Error)]
8#[serde(rename_all = "snake_case", tag = "kind")]
9#[non_exhaustive]
10pub enum ServiceError {
11 #[error("unreachable: {message}")]
13 Unreachable { message: String },
14 #[error("refused: {reason}")]
17 Refused { reason: String },
18 #[error("not found: {message}")]
20 NotFound { message: String },
21 #[error("bad request: {message}")]
23 BadRequest { message: String },
24 #[error("not supported: {message}")]
26 Unsupported { message: String },
27 #[error("busy")]
29 Busy,
30 #[error("unavailable: {message}")]
32 Unavailable { message: String },
33 #[error("{code}: {message}")]
35 App { code: String, message: String },
36 #[error("failed: {message}")]
38 Failed { message: String },
39 #[error("protocol error: {message}")]
41 Protocol { message: String },
42 #[error("connection closed")]
44 Closed,
45 #[error("timed out")]
47 Timeout,
48 #[error("cancelled")]
50 Cancelled,
51 #[serde(other)]
53 #[error("unknown error")]
54 Other,
55}
56
57impl ServiceError {
58 pub fn refused(reason: impl Into<String>) -> Self {
59 Self::Refused { reason: reason.into() }
60 }
61
62 pub fn not_found(message: impl Into<String>) -> Self {
63 Self::NotFound { message: message.into() }
64 }
65
66 pub fn bad_request(message: impl Into<String>) -> Self {
67 Self::BadRequest { message: message.into() }
68 }
69
70 pub fn unsupported(message: impl Into<String>) -> Self {
71 Self::Unsupported { message: message.into() }
72 }
73
74 pub fn unavailable(message: impl Into<String>) -> Self {
75 Self::Unavailable { message: message.into() }
76 }
77
78 pub fn app(code: impl Into<String>, message: impl Into<String>) -> Self {
79 Self::App { code: code.into(), message: message.into() }
80 }
81
82 pub fn failed(message: impl Into<String>) -> Self {
83 Self::Failed { message: message.into() }
84 }
85
86 pub fn protocol(message: impl Into<String>) -> Self {
87 Self::Protocol { message: message.into() }
88 }
89
90 pub fn is_permanent(&self) -> bool {
94 matches!(
95 self,
96 Self::Refused { .. } | Self::NotFound { .. } | Self::BadRequest { .. } | Self::Unsupported { .. } | Self::App { .. } | Self::Other
97 )
98 }
99}
100
101#[cfg(test)]
102mod tests {
103 use super::*;
104 use crate::codec::{from_cbor, to_cbor};
105
106 #[test]
107 fn errors_round_trip_and_unknown_kinds_decode() {
108 for e in [ServiceError::refused("role"), ServiceError::Closed, ServiceError::app("limit", "over the daily limit")] {
109 assert_eq!(from_cbor::<ServiceError>(&to_cbor(&e).unwrap()).unwrap(), e);
110 }
111 #[derive(Serialize)]
112 struct Future {
113 kind: &'static str,
114 detail: u32,
115 }
116 let newer = to_cbor(&Future { kind: "quota_exceeded", detail: 3 }).unwrap();
117 assert_eq!(from_cbor::<ServiceError>(&newer).unwrap(), ServiceError::Other);
118 assert!(ServiceError::refused("x").is_permanent() && !ServiceError::Timeout.is_permanent());
119 }
120}