icedwright_protocol/
error.rs1use core::fmt;
4
5use serde::{Deserialize, Serialize};
6
7use crate::version::VersionMismatch;
8
9#[derive(Debug, Clone, PartialEq, thiserror::Error)]
11#[non_exhaustive]
12pub enum ProtocolError {
13 #[error("frame of {0} bytes is over the 64 MiB limit")]
15 FrameTooLarge(u64),
16 #[error("malformed frame: {0}")]
19 Malformed(String),
20 #[error(transparent)]
22 Version(#[from] VersionMismatch),
23 #[error("{code}: {message}")]
25 Reply {
26 code: ErrorCode,
28 message: String,
30 },
31}
32
33impl From<ErrorBody> for ProtocolError {
34 fn from(body: ErrorBody) -> Self {
35 ProtocolError::Reply {
36 code: body.code,
37 message: body.message,
38 }
39 }
40}
41
42#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize)]
44#[serde(rename_all = "snake_case")]
45#[non_exhaustive]
46pub enum ErrorCode {
47 ProtocolMismatch,
49 BadRequest,
51 NoSuchWindow,
53 Stale,
55 NotReady,
57 Busy,
59 Refused,
61 Internal,
63}
64
65impl ErrorCode {
66 #[must_use]
68 pub const fn name(self) -> &'static str {
69 match self {
70 ErrorCode::ProtocolMismatch => "protocol_mismatch",
71 ErrorCode::BadRequest => "bad_request",
72 ErrorCode::NoSuchWindow => "no_such_window",
73 ErrorCode::Stale => "stale",
74 ErrorCode::NotReady => "not_ready",
75 ErrorCode::Busy => "busy",
76 ErrorCode::Refused => "refused",
77 ErrorCode::Internal => "internal",
78 }
79 }
80}
81
82impl fmt::Display for ErrorCode {
83 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
84 f.write_str(self.name())
85 }
86}
87
88#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
90pub struct ErrorBody {
91 pub code: ErrorCode,
93 pub message: String,
95}
96
97impl ErrorBody {
98 #[must_use]
100 pub fn new(code: ErrorCode, message: impl Into<String>) -> Self {
101 Self {
102 code,
103 message: message.into(),
104 }
105 }
106}
107
108#[cfg(test)]
109mod tests {
110 use super::*;
111
112 #[test]
113 fn codes_serialise_as_their_names() -> Result<(), serde_json::Error> {
114 for code in [
115 ErrorCode::ProtocolMismatch,
116 ErrorCode::BadRequest,
117 ErrorCode::NoSuchWindow,
118 ErrorCode::Stale,
119 ErrorCode::NotReady,
120 ErrorCode::Busy,
121 ErrorCode::Refused,
122 ErrorCode::Internal,
123 ] {
124 assert_eq!(serde_json::to_string(&code)?, format!("\"{code}\""));
125 }
126 Ok(())
127 }
128
129 #[test]
130 fn reply_errors_print_code_and_message() {
131 let error = ProtocolError::from(ErrorBody::new(ErrorCode::Stale, "the node moved"));
132 assert_eq!(error.to_string(), "stale: the node moved");
133 }
134}