1use std::fmt;
4
5use crate::prop::PropValue;
6
7#[derive(Clone, Debug, PartialEq)]
9pub enum Error {
10 InvalidId,
12 Busy(String),
15 UnknownClass(String),
16 UnknownProperty(String),
17 TypeMismatch { property: String, expected: &'static str, got: &'static str },
18 InvalidValue { property: String, message: String },
19 ReadOnly(String),
20 ComponentNotFound(String),
21 InvalidName(String),
22 DuplicateName(String),
23 Cycle,
25 FormNotCreated { name: String, message: String },
27}
28
29impl Error {
30 pub(crate) fn type_mismatch(expected: &'static str, got: &PropValue) -> Self {
31 Error::TypeMismatch { property: String::new(), expected, got: got.kind_name() }
32 }
33
34 pub(crate) fn invalid(message: impl Into<String>) -> Self {
35 Error::InvalidValue { property: String::new(), message: message.into() }
36 }
37
38 pub fn with_property(self, name: &str) -> Self {
40 match self {
41 Error::TypeMismatch { property, expected, got } if property.is_empty() => {
42 Error::TypeMismatch { property: name.to_string(), expected, got }
43 }
44 Error::InvalidValue { property, message } if property.is_empty() => {
45 Error::InvalidValue { property: name.to_string(), message }
46 }
47 other => other,
48 }
49 }
50}
51
52impl fmt::Display for Error {
53 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
54 match self {
55 Error::InvalidId => write!(f, "componente inexistente ou já liberado"),
56 Error::Busy(path) => write!(
57 f,
58 "{path} está ocupado: um método dele está rodando. Dentro do componente, use `self`; num componente \
59 composto, o pai lê os filhos, e o filho avisa o pai por evento"
60 ),
61 Error::UnknownClass(c) => write!(f, "classe '{c}' não registrada"),
62 Error::UnknownProperty(p) => write!(f, "propriedade '{p}' não existe"),
63 Error::TypeMismatch { property, expected, got } => {
64 write!(f, "propriedade '{property}': esperado {expected}, recebido {got}")
65 }
66 Error::InvalidValue { property, message } => write!(f, "propriedade '{property}': {message}"),
67 Error::ReadOnly(p) => write!(f, "propriedade '{p}' é somente leitura"),
68 Error::ComponentNotFound(n) => write!(f, "componente '{n}' não encontrado"),
69 Error::InvalidName(n) => write!(f, "nome inválido: '{n}'"),
70 Error::DuplicateName(n) => write!(f, "já existe um componente chamado '{n}'"),
71 Error::Cycle => {
72 write!(f, "um componente não pode ser filho de si mesmo ou de um descendente")
73 }
74 Error::FormNotCreated { name, message } => write!(f, "form '{name}': {message}"),
75 }
76 }
77}
78
79impl std::error::Error for Error {}
80
81pub type Result<T, E = Error> = std::result::Result<T, E>;