1
0
mirror of https://github.com/actix/actix-website synced 2025-02-13 00:25:35 +01:00
actix-website/examples/errors/src/override_error.rs

62 lines
1.4 KiB
Rust
Raw Normal View History

2019-06-17 13:46:21 -04:00
// <override>
2020-09-12 16:21:54 +01:00
use actix_web::{
2022-02-26 03:56:24 +00:00
error, get,
http::{header::ContentType, StatusCode},
App, HttpResponse,
2020-09-12 16:21:54 +01:00
};
use derive_more::{Display, Error};
2019-06-17 13:46:21 -04:00
2020-09-12 16:21:54 +01:00
#[derive(Debug, Display, Error)]
2019-06-17 13:46:21 -04:00
enum MyError {
2020-09-12 16:21:54 +01:00
#[display(fmt = "internal error")]
2019-06-17 13:46:21 -04:00
InternalError,
2020-09-12 16:21:54 +01:00
#[display(fmt = "bad request")]
2019-06-17 13:46:21 -04:00
BadClientData,
2020-09-12 16:21:54 +01:00
#[display(fmt = "timeout")]
2019-06-17 13:46:21 -04:00
Timeout,
}
impl error::ResponseError for MyError {
fn error_response(&self) -> HttpResponse {
2022-02-26 03:56:24 +00:00
HttpResponse::build(self.status_code())
.insert_header(ContentType::html())
.body(self.to_string())
}
fn status_code(&self) -> StatusCode {
2019-06-17 13:46:21 -04:00
match *self {
MyError::InternalError => StatusCode::INTERNAL_SERVER_ERROR,
MyError::BadClientData => StatusCode::BAD_REQUEST,
MyError::Timeout => StatusCode::GATEWAY_TIMEOUT,
2019-06-17 13:46:21 -04:00
}
}
}
2020-09-12 16:21:54 +01:00
#[get("/")]
async fn index() -> Result<&'static str, MyError> {
2019-06-17 13:46:21 -04:00
Err(MyError::BadClientData)
}
// </override>
2020-09-12 16:21:54 +01:00
#[get("/e2")]
async fn error2() -> Result<&'static str, MyError> {
Err(MyError::InternalError)
}
2020-09-12 16:21:54 +01:00
#[get("/e3")]
async fn error3() -> Result<&'static str, MyError> {
Err(MyError::Timeout)
}
2019-06-24 21:18:30 -04:00
2020-09-12 16:21:54 +01:00
#[actix_web::main]
async fn main() -> std::io::Result<()> {
2019-06-24 21:18:30 -04:00
use actix_web::HttpServer;
2020-09-12 16:21:54 +01:00
HttpServer::new(|| App::new().service(index).service(error2).service(error3))
2022-02-26 03:56:24 +00:00
.bind(("127.0.0.1", 8080))?
2020-09-12 16:21:54 +01:00
.run()
.await
2019-06-24 21:18:30 -04:00
}