vvv_engine/protocol/
failure.rs1use serde::{Deserialize, Serialize};
5
6#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize)]
8#[serde(rename_all = "snake_case")]
9pub enum ErrorCode {
10 BadRequest,
12 BadQuery,
14 BadPattern,
16 BadSelection,
18 BadTemplate,
20 NoSuchSymbol,
22 AmbiguousSymbol,
24 NoLanguage,
26 NoLayout,
28 NoSuchPosition,
30 Exists,
32 NotFound,
34 Unmovable,
36 Conflict,
38 Stale,
40 NoHistory,
42 Io,
44}
45
46#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
48pub struct Failure {
49 pub code: ErrorCode,
50 pub message: String,
51 #[serde(default, skip_serializing_if = "Option::is_none")]
53 pub hint: Option<String>,
54}
55
56impl Failure {
57 pub fn new(code: ErrorCode, message: impl Into<String>) -> Self {
58 Self {
59 code,
60 message: message.into(),
61 hint: None,
62 }
63 }
64
65 pub fn with_hint(mut self, hint: impl Into<String>) -> Self {
66 self.hint = Some(hint.into());
67 self
68 }
69}
70
71impl std::fmt::Display for Failure {
72 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
73 f.write_str(&self.message)
74 }
75}
76
77#[cfg(test)]
78mod tests {
79 use super::ErrorCode;
80
81 #[test]
85 fn every_code_keeps_its_wire_spelling() {
86 for code in [
87 ErrorCode::BadRequest,
88 ErrorCode::BadQuery,
89 ErrorCode::BadPattern,
90 ErrorCode::BadSelection,
91 ErrorCode::BadTemplate,
92 ErrorCode::NoSuchSymbol,
93 ErrorCode::AmbiguousSymbol,
94 ErrorCode::NoLanguage,
95 ErrorCode::NoLayout,
96 ErrorCode::NoSuchPosition,
97 ErrorCode::Exists,
98 ErrorCode::NotFound,
99 ErrorCode::Unmovable,
100 ErrorCode::Conflict,
101 ErrorCode::Stale,
102 ErrorCode::NoHistory,
103 ErrorCode::Io,
104 ] {
105 let documented = match code {
106 ErrorCode::BadRequest => "bad_request",
107 ErrorCode::BadQuery => "bad_query",
108 ErrorCode::BadPattern => "bad_pattern",
109 ErrorCode::BadSelection => "bad_selection",
110 ErrorCode::BadTemplate => "bad_template",
111 ErrorCode::NoSuchSymbol => "no_such_symbol",
112 ErrorCode::AmbiguousSymbol => "ambiguous_symbol",
113 ErrorCode::NoLanguage => "no_language",
114 ErrorCode::NoLayout => "no_layout",
115 ErrorCode::NoSuchPosition => "no_such_position",
116 ErrorCode::Exists => "exists",
117 ErrorCode::NotFound => "not_found",
118 ErrorCode::Unmovable => "unmovable",
119 ErrorCode::Conflict => "conflict",
120 ErrorCode::Stale => "stale",
121 ErrorCode::NoHistory => "no_history",
122 ErrorCode::Io => "io",
123 };
124 assert_eq!(
125 serde_json::to_value(code).unwrap(),
126 documented,
127 "docs/protocol.md documents `{documented}`"
128 );
129 }
130 }
131}