1
0
mirror of https://github.com/actix/examples synced 2025-02-10 12:44:14 +01:00

47 lines
1.3 KiB
Rust
Raw Normal View History

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
2024-01-30 23:44:35 +00:00
use std::{fmt, io};
2022-02-25 21:07:22 +00:00
use actix_web::{http::StatusCode, web, App, HttpResponse, HttpServer, ResponseError};
2019-06-22 02:08:18 -05:00
use serde::Serialize;
#[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
}
2024-01-30 23:44:35 +00:00
impl fmt::Display for Error {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
write!(f, "{}", serde_json::to_string_pretty(self).unwrap())
2019-07-11 15:02:25 +06:00
}
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 {
2024-01-30 23:44:35 +00:00
let err_json = serde_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))))
2024-01-30 23:44:35 +00:00
.workers(2)
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
}