1
0
mirror of https://github.com/actix/actix-website synced 2024-12-18 18:03:12 +01:00
actix-website/examples/errors/src/recommend_one.rs

43 lines
1.0 KiB
Rust
Raw Normal View History

2019-06-17 19:46:21 +02:00
// <recommend-one>
2020-09-12 17:21:54 +02:00
use actix_web::{
2022-02-26 04:56:24 +01:00
error, get,
http::{header::ContentType, StatusCode},
App, HttpResponse, HttpServer,
2020-09-12 17:21:54 +02:00
};
use derive_more::derive::{Display, Error};
2019-06-17 19:46:21 +02:00
2020-09-12 17:21:54 +02:00
#[derive(Debug, Display, Error)]
2019-06-17 19:46:21 +02:00
enum UserError {
#[display("Validation error on field: {field}")]
2019-06-17 19:46:21 +02:00
ValidationError { field: String },
}
impl error::ResponseError for UserError {
fn error_response(&self) -> HttpResponse {
2022-02-26 04:56:24 +01:00
HttpResponse::build(self.status_code())
.insert_header(ContentType::html())
.body(self.to_string())
}
fn status_code(&self) -> StatusCode {
2019-06-17 19:46:21 +02:00
match *self {
UserError::ValidationError { .. } => StatusCode::BAD_REQUEST,
2019-06-17 19:46:21 +02:00
}
}
}
// </recommend-one>
2020-09-12 17:21:54 +02:00
#[get("/")]
async fn index() -> Result<&'static str, UserError> {
Err(UserError::ValidationError {
field: "bad stuff".to_string(),
})
}
2019-06-25 03:18:30 +02:00
2020-09-12 17:21:54 +02:00
#[actix_web::main]
async fn main() -> std::io::Result<()> {
2020-09-12 17:21:54 +02:00
HttpServer::new(|| App::new().service(index))
2022-02-26 04:56:24 +01:00
.bind(("127.0.0.1", 8080))?
2019-06-25 03:18:30 +02:00
.run()
.await
2019-06-25 03:18:30 +02:00
}