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