Certainly! The issue you're encountering is that the closure inside the .map() call doesn't return the correct type, and it also needs to propagate errors properly.
To handle this, you can use the and_then method instead of map, which allows you to return a Result from the closure. This will enable you to properly handle and propagate errors.
Here's how you can refactor your code:
use uuid::Uuid;
use thiserror::Error;
// Assuming these are your structs and error types
#[derive(Debug)]
struct Album {
// fields here
}
#[derive(Debug, Error)]
enum AlbumConversionError {
#[error("Failed to parse UUID")]
ParseUuidError(uuid::Error),
#[error("Year is less than or equal to zero: {0}")]
YearLessOrEqualToZero(i64),
// other errors here
}
impl Album {
fn new(id: Uuid, name: String, artist_id: Uuid, year: Option<u32>) -> Result<Self, AlbumConversionError> {
// implementation here
unimplemented!()
}
}
#[derive(Debug)]
struct DbAlbum {
id: Vec<u8>,
name: String,
artist_id: Vec<u8>,
year: Option<i64>,
}
impl TryFrom<DbAlbum> for Album {
type Error = AlbumConversionError;
fn try_from(db_album: DbAlbum) -> Result<Self, Self::Error> {
let id = Uuid::from_slice(&db_album.id).map_err(AlbumConversionError::ParseUuidError)?;
let artist_id = Uuid::from_slice(&db_album.artist_id).map_err(AlbumConversionError::ParseUuidError)?;
let year = db_album.year.and_then(|int_64| {
if int_64 <= 0 {
return Err(AlbumConversionError::YearLessOrEqualToZero(int_64));
}
Some(int_64 as u32)
});
Ok(Self::new(id, db_album.name, artist_id, year)?)
}
}
Explanation:
-
Using and_then:
- The
and_then method is used to apply a function that returns a Result or Option to an Option. This allows you to handle errors within the closure.
-
Error Handling:
- The
Uuid::from_slice calls are wrapped with map_err to convert uuid::Error into AlbumConversionError.
- The year validation is done inside the
and_then closure, which returns an Option<u32> or an error.
-
Propagating Errors:
- The
? operator is used to propagate errors from Self::new and the Uuid::from_slice calls.
This should correctly handle the validation and error propagation within your try_from implementation.