Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Consider adding context-aware error handling library #129

Open
akoshelev opened this issue Oct 15, 2022 · 1 comment
Open

Consider adding context-aware error handling library #129

akoshelev opened this issue Oct 15, 2022 · 1 comment

Comments

@akoshelev
Copy link
Collaborator

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.

async fn send_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

async fn send_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?
}

impl From<Context<IpAddr, SendError>> for MyError {
    fn from(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

and probably more. We can consider using one of them

@akoshelev
Copy link
Collaborator Author

Alternatively we could implement context on errors by ourselves - it is not that hard compared to migrating to eyer/snafu/anyhow

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant