1
0
mirror of https://github.com/actix/examples synced 2025-02-09 20:25:37 +01:00

50 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
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 {
2019-07-11 15:02:25 +06:00
msg: "an example error message".to_string(),
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<()> {
2019-07-11 15:02:25 +06:00
let ip_address = "127.0.0.1:8000";
println!("Running server on {}", ip_address);
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))))
.bind(ip_address)
.expect("Can not bind to port 8000")
.run()
.await
2019-06-22 02:08:18 -05:00
}