2019-06-22 02:08:18 -05:00
|
|
|
// This example is meant to show how to automatically generate a json error response when something goes wrong.
|
|
|
|
|
|
|
|
use actix::System;
|
|
|
|
use actix_web::http::StatusCode;
|
|
|
|
use actix_web::web::{get, resource, HttpRequest, HttpResponse};
|
|
|
|
use actix_web::{App, HttpServer, ResponseError};
|
|
|
|
use futures::future::err;
|
|
|
|
use futures::Future;
|
|
|
|
use serde::Serialize;
|
|
|
|
use serde_json::{json, to_string_pretty};
|
|
|
|
use std::fmt::{Display, Formatter, Result as FmtResult};
|
|
|
|
use std::io;
|
|
|
|
|
|
|
|
#[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
|
|
|
|
fn render_response(&self) -> HttpResponse {
|
|
|
|
let err_json = json!({ "error": self.msg });
|
|
|
|
HttpResponse::build(StatusCode::from_u16(self.status).unwrap()).json(err_json)
|
|
|
|
}
|
2019-06-22 02:08:18 -05:00
|
|
|
}
|
|
|
|
|
|
|
|
fn index(_: HttpRequest) -> impl Future<Item = HttpResponse, Error = Error> {
|
2019-07-11 15:02:25 +06:00
|
|
|
err(Error {
|
|
|
|
msg: "an example error message".to_string(),
|
|
|
|
status: 400,
|
|
|
|
})
|
2019-06-22 02:08:18 -05:00
|
|
|
}
|
|
|
|
|
|
|
|
fn main() -> io::Result<()> {
|
2019-07-11 15:02:25 +06:00
|
|
|
let sys = System::new("json_error_example");
|
|
|
|
let ip_address = "127.0.0.1:8000";
|
2019-06-22 02:08:18 -05:00
|
|
|
|
2019-07-11 15:02:25 +06:00
|
|
|
HttpServer::new(|| App::new().service(resource("/").route(get().to_async(index))))
|
|
|
|
.bind(ip_address)
|
|
|
|
.expect("Can not bind to port 8000")
|
|
|
|
.start();
|
2019-06-22 02:08:18 -05:00
|
|
|
|
2019-07-11 15:02:25 +06:00
|
|
|
println!("Running server on {}", ip_address);
|
2019-06-22 02:08:18 -05:00
|
|
|
|
2019-07-11 15:02:25 +06:00
|
|
|
sys.run()
|
2019-06-22 02:08:18 -05:00
|
|
|
}
|