You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
It is often useful to provide additional context when converting error types which is impossible while using standard From and TryFrom implementations. For example, it is useful to record the destination address when send request fails. Often, the error types provided by the underlying libraries do not carry this information.
One way to handle this is to use map_err, however the code written that way tend to be repeatable and carry details that are not that important.
asyncfnsend_request(dest:IpAddr) -> Result<(),MyError>{let destination_ip = "127.0.0.1:80".try_into().unwrap();let r = send("hello", destination_ip).await.map_err(|e| MyError::new(format!("Failed to send to {destination_ip}", e))}
More elegant code that uses context aware error handling libraries may look like this
asyncfnsend_request(dest:IpAddr) -> Result<(),MyError>{let destination_ip = "127.0.0.1:80".try_into().unwrap();let r = send("hello", destination_ip).context(dest).await?
}implFrom<Context<IpAddr,SendError>>forMyError{fnfrom(source:Context<IpAddr,SendError>) -> Self{MyError::new(format!("Failed to send to {destination_ip}", e)}}
While standard library does not provide any API for that (however it is in the roadmap), there are several different libraries that implement this pattern
It is often useful to provide additional context when converting error types which is impossible while using standard
From
andTryFrom
implementations. For example, it is useful to record the destination address when send request fails. Often, the error types provided by the underlying libraries do not carry this information.One way to handle this is to use
map_err
, however the code written that way tend to be repeatable and carry details that are not that important.More elegant code that uses context aware error handling libraries may look like this
While standard library does not provide any API for that (however it is in the roadmap), there are several different libraries that implement this pattern
and probably more. We can consider using one of them
The text was updated successfully, but these errors were encountered: