2022-02-25 21:07:22 +00:00
|
|
|
//! This example is meant to show how to automatically generate a json error response when something goes wrong.
|
2019-06-22 02:08:18 -05:00
|
|
|
|
2022-02-25 21:07:22 +00:00
|
|
|
use std::{
|
|
|
|
fmt::{Display, Formatter, Result as FmtResult},
|
|
|
|
io,
|
|
|
|
};
|
|
|
|
|
|
|
|
use actix_web::{http::StatusCode, web, App, HttpResponse, HttpServer, ResponseError};
|
2019-06-22 02:08:18 -05:00
|
|
|
use serde::Serialize;
|
|
|
|
use serde_json::{json, to_string_pretty};
|
|
|
|
|
|
|
|
#[derive(Debug, Serialize)]
|
|
|
|
struct Error {
|
2019-07-11 15:02:25 +06:00
|
|
|
msg: String,
|
|
|
|
status: u16,
|
2019-06-22 02:08:18 -05:00
|
|
|
}
|
|
|
|
|
|
|
|
impl Display for Error {
|
2019-07-11 15:02:25 +06:00
|
|
|
fn fmt(&self, f: &mut Formatter) -> FmtResult {
|
|
|
|
write!(f, "{}", to_string_pretty(self).unwrap())
|
|
|
|
}
|
2019-06-22 02:08:18 -05:00
|
|
|
}
|
|
|
|
|
|
|
|
impl ResponseError for Error {
|
2019-07-11 15:02:25 +06:00
|
|
|
// builds the actual response to send back when an error occurs
|
2022-02-25 21:07:22 +00:00
|
|
|
fn error_response(&self) -> HttpResponse {
|
2019-07-11 15:02:25 +06:00
|
|
|
let err_json = json!({ "error": self.msg });
|
2022-02-25 21:07:22 +00:00
|
|
|
HttpResponse::build(StatusCode::from_u16(self.status).unwrap()).json(err_json)
|
2019-07-11 15:02:25 +06:00
|
|
|
}
|
2019-06-22 02:08:18 -05:00
|
|
|
}
|
|
|
|
|
2022-02-25 21:07:22 +00:00
|
|
|
async fn index() -> Result<HttpResponse, Error> {
|
2019-12-07 23:59:24 +06:00
|
|
|
Err(Error {
|
2023-07-09 03:32:47 +01:00
|
|
|
msg: "an example error message".to_owned(),
|
2019-07-11 15:02:25 +06:00
|
|
|
status: 400,
|
|
|
|
})
|
2019-06-22 02:08:18 -05:00
|
|
|
}
|
|
|
|
|
2020-09-12 16:49:45 +01:00
|
|
|
#[actix_web::main]
|
2019-12-07 23:59:24 +06:00
|
|
|
async fn main() -> io::Result<()> {
|
2022-03-06 00:41:32 +00:00
|
|
|
env_logger::init_from_env(env_logger::Env::new().default_filter_or("info"));
|
|
|
|
|
|
|
|
log::info!("starting HTTP server at http://localhost:8080");
|
2019-06-22 02:08:18 -05:00
|
|
|
|
2022-02-18 02:44:02 +00:00
|
|
|
HttpServer::new(|| App::new().service(web::resource("/").route(web::get().to(index))))
|
2022-03-06 00:41:32 +00:00
|
|
|
.bind(("127.0.0.1", 8080))?
|
2022-02-18 02:44:02 +00:00
|
|
|
.run()
|
|
|
|
.await
|
2019-06-22 02:08:18 -05:00
|
|
|
}
|