【Rust】reqwestのresponseでstatusコードによって切り分ける

error_for_status() で、エラーレスポンスの場合を取得できる。
https://docs.rs/reqwest/latest/reqwest/struct.Response.html
200の場合は通過する。

pub async fn handle_health() -> Response {
    (StatusCode::OK, format!("I'm ACTIVE")).into_response()
    // (StatusCode::BAD_REQUEST, format!("Something wrong happened")).into_response()
}

async fn handle_post_test()-> Response {
    let res = reqwest::get("http://192.168.33.10:3000/health").await;
    match res.unwrap().error_for_status() {
        Ok(_res) => {
            println!("health check is OK");
        },
        Err(_err) => {
            println!("got bad request response. something wrong");
        }
    }
    //
}

なるほど〜

レスポンスで、statusコードをStatusCode::OKと返却しない場合でも、.error_for_status()は通過する。

// OK
(StatusCode::OK, format!(“I’m ACTIVE”)).into_response()
// OK
“All good”.into_response()
// Err
(StatusCode::BAD_REQUEST, format!(“Something wrong happened”)).into_response()