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

40 lines
1.1 KiB
Rust
Raw Normal View History

2019-06-17 19:46:21 +02:00
// <recommend-one>
use actix_http::ResponseBuilder;
use actix_web::{error, http::header, http::StatusCode, HttpResponse};
2019-06-17 19:46:21 +02:00
use failure::Fail;
#[derive(Fail, Debug)]
enum UserError {
#[fail(display = "Validation error on field: {}", field)]
ValidationError { field: String },
}
impl error::ResponseError for UserError {
fn error_response(&self) -> HttpResponse {
ResponseBuilder::new(self.status_code())
.set_header(header::CONTENT_TYPE, "text/html; charset=utf-8")
.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>
async fn index() -> Result<&'static str, UserError> {
Err(UserError::ValidationError {
field: "bad stuff".to_string(),
})
}
2019-06-25 03:18:30 +02:00
#[actix_rt::main]
async fn main() -> std::io::Result<()> {
2019-06-25 03:18:30 +02:00
use actix_web::{web, App, HttpServer};
HttpServer::new(|| App::new().route("/", web::get().to(index)))
.bind("127.0.0.1:8088")?
2019-06-25 03:18:30 +02:00
.run()
.await
2019-06-25 03:18:30 +02:00
}