use puerto_core::RepositoryError;
use thiserror::Error;
#[derive(Debug, Error)]
pub enum {{ pascal }}Error {
#[error("{{ snake }}.validation_error.{0}")]
ValidationError(String),
#[error("{{ snake }}.not_found")]
NotFound,
#[error("{{ snake }}.duplicate")]
Duplicate,
#[error("{{ snake }}.repository_error")]
RepositoryError,
#[error("{{ snake }}.unknown")]
Unknown,
{% if auth %} /// The caller may not do this with this data: a rule of the use case, on its `actor`.
#[error("{{ snake }}.forbidden")]
Forbidden,
{% endif %}{% for f in vo_fields %} #[error("{{ snake }}.invalid_{{ f.vo_snake }}")]
Invalid{{ f.vo_pascal }},
{% endfor %}}
impl From<RepositoryError> for {{ pascal }}Error {
/// Every failure `puerto-core` names has its arm. `RepositoryError` is `#[non_exhaustive]`: one
/// a later version adds is the store's problem (500) until it gets a meaning here.
fn from(err: RepositoryError) -> Self {
match err {
RepositoryError::Duplicate => Self::Duplicate,
{% if references %} // A reference names a row that does not exist: the caller's input, on that field.
RepositoryError::MissingReference(field) => {
Self::ValidationError(format!("{field}_not_found"))
}
{% endif %} RepositoryError::InvalidData | RepositoryError::Unavailable => Self::RepositoryError,
_ => Self::RepositoryError,
}
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn should_convert_a_duplicate_into_the_entity_duplicate() {
let err = {{ pascal }}Error::from(RepositoryError::Duplicate);
assert_eq!(err.to_string(), "{{ snake }}.duplicate");
}
#[test]
fn should_convert_invalid_data_into_a_repository_error() {
let err = {{ pascal }}Error::from(RepositoryError::InvalidData);
assert_eq!(err.to_string(), "{{ snake }}.repository_error");
}
{% if references %} #[test]
fn should_convert_a_missing_reference_into_a_validation_error_on_its_field() {
let err = {{ pascal }}Error::from(RepositoryError::MissingReference("{{ first_reference }}"));
assert_eq!(err.to_string(), "{{ snake }}.validation_error.{{ first_reference }}_not_found");
}
{% endif %} #[test]
fn should_convert_an_unavailable_store_into_a_repository_error() {
let err = {{ pascal }}Error::from(RepositoryError::Unavailable);
assert_eq!(err.to_string(), "{{ snake }}.repository_error");
}
}