Skip to main content

ledger_models/fintekkers/wrappers/models/utils/
errors.rs

1use 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    /// Typed input error (docs/adr/typed-input-errors.md): the object has one
25    /// or more bad fields. Never empty. Maps to `Code::InvalidArgument`.
26    Validation(Vec<FieldViolationProto>),
27}
28
29impl Error {
30    /// Field-level violations of a `Validation` error; empty for other variants.
31    pub fn violations(&self) -> &[FieldViolationProto] {
32        match self {
33            Error::Validation(v) => v,
34            _ => &[],
35        }
36    }
37
38    /// Labels a `Validation` error with the field the caller decoded it from,
39    /// e.g. `deserialize_decimal(p).map_err(|e| e.in_field("price"))`. Every
40    /// violation is prefixed: an empty field becomes `name`, a field `f`
41    /// becomes `name.f`. Other variants are returned unchanged.
42    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
62/// The `object_id` for a violation: the object's UUID, or None when it has
63/// none or it is not 16 bytes. Shared by the `validate_*` rules.
64pub(crate) fn object_id_of(uuid: Option<&UuidProto>) -> Option<UuidProto> {
65    uuid.filter(|u| u.raw_uuid.len() == 16).cloned()
66}
67
68/// Joins violations as `<field>: <message> (id <uuid>)`, separated by `; `,
69/// the same shape as Java's ModelValidationException message. A violation
70/// with no field (an unlabelled decode error) is `<message> (id <uuid>)`.
71fn 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    /// Display joins the violations, so callers need no formatter of their
131    /// own (LM-312). The `(id null)` suffix matches Java's message.
132    #[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}