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
status()reports what the server said.error_for_statusturns 4xx and 5xx into anErr.is_timeoutandis_connectclassify transport failures.
Keywords and builtins used here
ErrOkasyncawaitfnletmainmatch
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.
Step 4 of 5 in Requests with reqwest, step 10 of 12 in CLI tools & HTTP clients.