Skip to main content

bern_protocol/
error.rs

1use serde::{Deserialize, Serialize};
2use std::fmt;
3
4/// Structured command failure returned identically to every entry point.
5#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
6pub struct CommandError {
7    pub code: String,
8    pub message: String,
9}
10
11impl CommandError {
12    pub fn new(code: impl Into<String>, message: impl Into<String>) -> Self {
13        Self {
14            code: code.into(),
15            message: message.into(),
16        }
17    }
18
19    pub fn invalid_params(message: impl Into<String>) -> Self {
20        Self::new("invalid_params", message)
21    }
22
23    pub fn unknown_command(command: &str) -> Self {
24        Self::new("unknown_command", format!("unknown command `{command}`"))
25    }
26}
27
28impl fmt::Display for CommandError {
29    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
30        write!(f, "{}: {}", self.code, self.message)
31    }
32}
33
34impl std::error::Error for CommandError {}
35
36impl From<SchemaError> for CommandError {
37    fn from(error: SchemaError) -> Self {
38        CommandError::invalid_params(error.message)
39    }
40}
41
42/// A value or definition that does not match the declared schema.
43#[derive(Clone, Debug, PartialEq, Eq)]
44pub struct SchemaError {
45    pub message: String,
46}
47
48impl SchemaError {
49    pub fn new(message: impl Into<String>) -> Self {
50        Self {
51            message: message.into(),
52        }
53    }
54}
55
56impl fmt::Display for SchemaError {
57    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
58        f.write_str(&self.message)
59    }
60}
61
62impl std::error::Error for SchemaError {}