use core::fmt;
use serde::{Deserialize, Serialize};
use crate::version::VersionMismatch;
#[derive(Debug, Clone, PartialEq, thiserror::Error)]
#[non_exhaustive]
pub enum ProtocolError {
#[error("frame of {0} bytes is over the 64 MiB limit")]
FrameTooLarge(u64),
#[error("malformed frame: {0}")]
Malformed(String),
#[error(transparent)]
Version(#[from] VersionMismatch),
#[error("{code}: {message}")]
Reply {
code: ErrorCode,
message: String,
},
}
impl From<ErrorBody> for ProtocolError {
fn from(body: ErrorBody) -> Self {
ProtocolError::Reply {
code: body.code,
message: body.message,
}
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
#[non_exhaustive]
pub enum ErrorCode {
ProtocolMismatch,
BadRequest,
NoSuchWindow,
Stale,
NotReady,
Busy,
Refused,
Internal,
}
impl ErrorCode {
#[must_use]
pub const fn name(self) -> &'static str {
match self {
ErrorCode::ProtocolMismatch => "protocol_mismatch",
ErrorCode::BadRequest => "bad_request",
ErrorCode::NoSuchWindow => "no_such_window",
ErrorCode::Stale => "stale",
ErrorCode::NotReady => "not_ready",
ErrorCode::Busy => "busy",
ErrorCode::Refused => "refused",
ErrorCode::Internal => "internal",
}
}
}
impl fmt::Display for ErrorCode {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.write_str(self.name())
}
}
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct ErrorBody {
pub code: ErrorCode,
pub message: String,
}
impl ErrorBody {
#[must_use]
pub fn new(code: ErrorCode, message: impl Into<String>) -> Self {
Self {
code,
message: message.into(),
}
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn codes_serialise_as_their_names() -> Result<(), serde_json::Error> {
for code in [
ErrorCode::ProtocolMismatch,
ErrorCode::BadRequest,
ErrorCode::NoSuchWindow,
ErrorCode::Stale,
ErrorCode::NotReady,
ErrorCode::Busy,
ErrorCode::Refused,
ErrorCode::Internal,
] {
assert_eq!(serde_json::to_string(&code)?, format!("\"{code}\""));
}
Ok(())
}
#[test]
fn reply_errors_print_code_and_message() {
let error = ProtocolError::from(ErrorBody::new(ErrorCode::Stale, "the node moved"));
assert_eq!(error.to_string(), "stale: the node moved");
}
}