Skip to content
This repository has been archived by the owner on Mar 3, 2020. It is now read-only.

Error handling in async for loop #25

Open
phaux opened this issue Sep 6, 2017 · 2 comments
Open

Error handling in async for loop #25

phaux opened this issue Sep 6, 2017 · 2 comments

Comments

@phaux
Copy link

phaux commented Sep 6, 2017

Wouldn't it be better if the whole async for loop expression evaluated to a possible Err<Stream::Error> if an error occured and Ok(()) otherwise? That way you can do some custom error handling.

Example 1:

let stream = get_stream();
let result = #[async] for message in stream {
    println!("{}", message);
};
if let Err(err) = result {
    println!("An error occured!");
}

Example 2:

let stream = get_stream();
#[async] for message in stream {
    println!("{}", message);
}.unwrap_or_else(|err| {
    println!("An error occured!");
});

To get the current behavior you just put ? after the loop body:

#[async] for message in stream {}?;
@alexcrichton
Copy link
Owner

Yeah this is something I'm not entirely sure how to handle. The ability though for a for loop to have a value isn't something I'd though of before, so may have something promising!

@Arnavion
Copy link

Arnavion commented Sep 9, 2017

You can do this right now by wrapping the loop in a catch block since #[async] for uses ? on the result of Stream::poll().

let stream = get_stream();
let result = do catch {
    #[async] for message in stream {
        println!("{}", message);
    }
    Ok(())
};
if let Err(err) = result {
    println!("An error occured!");
}

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

No branches or pull requests

3 participants