1
0
mirror of https://github.com/actix/actix-website synced 2025-02-02 12:19:04 +01:00
actix-website/examples/errors/src/recommend_two.rs

47 lines
1.2 KiB
Rust
Raw Normal View History

2019-06-17 13:46:21 -04:00
// <recommend-two>
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, HttpServer,
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 UserError {
2020-09-12 16:21:54 +01:00
#[display(fmt = "An internal error occurred. Please try again later.")]
2019-06-17 13:46:21 -04:00
InternalError,
}
impl error::ResponseError for UserError {
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())
}
2022-02-26 03:56:24 +00:00
fn status_code(&self) -> StatusCode {
2019-06-17 13:46:21 -04:00
match *self {
UserError::InternalError => StatusCode::INTERNAL_SERVER_ERROR,
2019-06-17 13:46:21 -04:00
}
}
}
2020-09-12 16:21:54 +01:00
#[get("/")]
async fn index() -> Result<&'static str, UserError> {
2020-09-12 16:21:54 +01:00
do_thing_that_fails().map_err(|_e| UserError::InternalError)?;
2019-06-17 13:46:21 -04:00
Ok("success!")
}
// </recommend-two>
2019-06-24 21:18:30 -04:00
2020-09-12 16:21:54 +01:00
fn do_thing_that_fails() -> Result<(), std::io::Error> {
2019-06-24 21:18:30 -04:00
Err(std::io::Error::new(std::io::ErrorKind::Other, "some error"))
}
2020-09-12 16:21:54 +01:00
#[actix_web::main]
async fn main() -> std::io::Result<()> {
2020-09-12 16:21:54 +01:00
HttpServer::new(|| App::new().service(index))
2022-02-26 03:56:24 +00:00
.bind(("127.0.0.1", 8080))?
2019-06-24 21:18:30 -04:00
.run()
.await
}