Rustのactix-webで条件を満たしたときにエラーレスポンスを返したく以下の通り実装しましたがエラーが出てしまいました。
#[post("/backends")]
async fn add_backend(
pool: web::Data<DbPool>,
form: web::Json<forms::BackendForm>,
) -> Result<HttpResponse, Error>{
let resp = reqwest::get(&format!("{}/version", form.url))
.await
.map_err(|e| {
eprintln!("{}", e);
HttpResponse::BadRequest().finish()
})?;
if resp.status() != http::StatusCode::OK{
HttpResponse::BadRequest().finish()
}
let version = resp.text()
.await
.map_err(|e| {
eprintln!("{}", e);
HttpResponse::BadRequest().finish()
})?;
if version == ""{
Ok(HttpResponse::BadRequest().finish())
}
let conn = pool.get().expect("cant get db pool");
let backend = web::block(move || actions::create_backend(&form.name, &form.url, &version, &conn))
.await
.map_err(|e| {
eprintln!("{}", e);
HttpResponse::InternalServerError().finish()
})?;
Ok(HttpResponse::Ok().json(backend))
}
error[E0308]: mismatched types
--> src/main.rs:58:9
|
57 | / if resp.status() != http::StatusCode::OK{
58 | | HttpResponse::BadRequest().finish()
| | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ expected `()`, found struct `actix_http::response::Response`
59 | | }
| |_____- expected this to be `()`
|
= note: expected unit type `()`
found struct `actix_http::response::Response`
help: try adding a semicolon
|
58 | HttpResponse::BadRequest().finish();
| ^
help: consider using a semicolon here
|
59 | };
| ^
error[E0308]: mismatched types
--> src/main.rs:69:9
|
68 | / if version == ""{
69 | | Ok(HttpResponse::BadRequest().finish())
| | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ expected `()`, found enum `std::result::Result`
70 | | }
| |_____- expected this to be `()`
|
= note: expected unit type `()`
found enum `std::result::Result<actix_http::response::Response, _>`
help: try adding a semicolon
|
69 | Ok(HttpResponse::BadRequest().finish());
| ^
help: consider using a semicolon here
|
70 | };
| ^
error: aborting due to 2 previous errors
finish()
の返り値はResult<HttpResponse, HttpError>
なのでこれで良いと考えましたがだめでした。
Ok
で包んでも同様のエラーが出てしまいます。セミコロンをつけることを推奨されていますが、つけるとエラーは消えますが、当然下まで実行されます。このような場合はどのように実装すれば良いのでしょうか。
参考: https://docs.rs/actix-web/0.3.1/actix_web/dev/struct.HttpResponseBuilder.html