How to Handle Errors in Async Functions in Rust

Handle async errors in Rust by returning Result types and using the ? operator to propagate failures gracefully.

Handle errors in async functions by returning Result<T, E> and propagating failures with the ? operator or match.

use trpl::Html;

async fn page_title(url: &str) -> Result<Option<String>, Box<dyn std::error::Error>> {
    let response = trpl::get(url).await?;
    let response_text = response.text().await?;
    let html = Html::parse(&response_text);
    Ok(html.select_first("title").map(|t| t.inner_html()))
}

This pattern ensures that if get or text fails, the error bubbles up immediately instead of crashing the runtime.