typestar

Status codes and failures in Rust

A 404 is a successful request with an unsuccessful status — handle both.

#[tokio::main]
async fn main() {
    match reqwest::get("https://typestar.io/missing").await {
        Ok(response) => {
            let code = response.status();
            println!("{} success={}", code, code.is_success());
            match response.error_for_status() {
                Ok(_) => println!("body is usable"),
                Err(e) => println!("bad status: {e}"),
            }
        }
        Err(e) => println!(
            "transport failed: timeout={} connect={}",
            e.is_timeout(),
            e.is_connect()
        ),
    }
}

How it works

  1. status() reports what the server said.
  2. error_for_status turns 4xx and 5xx into an Err.
  3. is_timeout and is_connect classify transport failures.

Keywords and builtins used here

The run, in numbers

Lines
18
Characters to type
407
Tokens
114
Three-star pace
110 tpm

At the three-star pace of 110 tokens a minute, this run takes about 62 seconds.

Type this snippet

Step 4 of 5 in Requests with reqwest, step 10 of 12 in CLI tools & HTTP clients.

← Previous Next →