ledger_models/fintekkers/wrappers/models/utils/
errors.rs1use crate::fintekkers::models::position::MeasureProto;
2use crate::fintekkers::models::util::UuidProto;
3use crate::fintekkers::requests::util::errors::FieldViolationProto;
4use crate::fintekkers::wrappers::models::utils::date::ParseError;
5use tonic::{Code, Status};
6
7#[derive(Debug)]
8pub enum Error {
9 MissingPositionInput,
10 MissingPriceInput,
11 MissingFaceValue,
12 MissingCouponRate,
13 MissingMaturityDate,
14 MissingIssueDate,
15 NotABondSecurity,
16 MissingSecurityInput,
17 MissingBaseCpi,
18 MissingCpi,
19 MissingMeasure(MeasureProto),
20 DecimalConversion,
21 DateConversion,
22 UuidError,
23 DeserializationError,
24 Validation(Vec<FieldViolationProto>),
27}
28
29impl Error {
30 pub fn violations(&self) -> &[FieldViolationProto] {
32 match self {
33 Error::Validation(v) => v,
34 _ => &[],
35 }
36 }
37
38 pub fn in_field(self, name: &str) -> Error {
43 match self {
44 Error::Validation(violations) => Error::Validation(
45 violations
46 .into_iter()
47 .map(|mut v| {
48 v.field = if v.field.is_empty() {
49 name.to_string()
50 } else {
51 format!("{}.{}", name, v.field)
52 };
53 v
54 })
55 .collect(),
56 ),
57 other => other,
58 }
59 }
60}
61
62pub(crate) fn object_id_of(uuid: Option<&UuidProto>) -> Option<UuidProto> {
65 uuid.filter(|u| u.raw_uuid.len() == 16).cloned()
66}
67
68fn describe_violations(violations: &[FieldViolationProto]) -> String {
72 violations
73 .iter()
74 .map(|v| {
75 let id = v
76 .object_id
77 .as_ref()
78 .and_then(|u| uuid::Uuid::from_slice(&u.raw_uuid).ok())
79 .map(|u| u.to_string())
80 .unwrap_or_else(|| "null".to_string());
81 if v.field.is_empty() {
82 format!("{} (id {})", v.message, id)
83 } else {
84 format!("{}: {} (id {})", v.field, v.message, id)
85 }
86 })
87 .collect::<Vec<_>>()
88 .join("; ")
89}
90
91impl std::fmt::Display for Error {
92 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
93 match self {
94 Error::Validation(v) => f.write_str(&describe_violations(v)),
95 other => write!(f, "{:?}", other),
96 }
97 }
98}
99
100impl From<ParseError> for Error {
101 fn from(_: ParseError) -> Self {
102 Error::DateConversion
103 }
104}
105
106impl From<Error> for Status {
107 fn from(value: Error) -> Self {
108 match value {
109 Error::DateConversion => Status::new(Code::Internal, "Failed to convert date"),
110 Error::DecimalConversion => Status::new(Code::Internal, "Failed to convert decimal"),
111 Error::DeserializationError => Status::new(Code::Internal, "Failed to deserialize protobuf message"),
112 Error::MissingMeasure(m) => Status::new(
113 Code::Internal,
114 format!("Missing measure {}", m.as_str_name()),
115 ),
116 Error::Validation(v) => Status::new(Code::InvalidArgument, describe_violations(&v)),
117 _ => Status::new(Code::InvalidArgument, format!("{:?}", value)),
118 }
119 }
120}
121
122#[cfg(test)]
123mod tests {
124 use super::*;
125
126 fn violation(message: &str) -> FieldViolationProto {
127 FieldViolationProto { field: String::new(), object_id: None, message: message.to_string() }
128 }
129
130 #[test]
133 fn display_joins_violations() {
134 let err = Error::Validation(vec![violation("a"), violation("b")]);
135 assert_eq!(err.to_string(), "a (id null); b (id null)");
136 }
137}