Created
January 19, 2021 16:29
-
-
Save fchabouis/08ba3651087b862ff0227bf9431d7df6 to your computer and use it in GitHub Desktop.
Actix-web example : return errors as json
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// This example is meant to show how to automatically generate a json error response when something goes wrong. | |
use std::fmt::{Display, Formatter, Result as FmtResult}; | |
use std::io; | |
use actix_web::http::StatusCode; | |
use actix_web::{get, web, App, HttpServer, ResponseError}; | |
use serde::Serialize; | |
use serde_json::{json, to_string_pretty}; | |
// We create a custom structure for the error | |
#[derive(Debug, Serialize)] | |
struct MyError { | |
msg: String, | |
status: u16, | |
} | |
// we implement the display trait | |
impl Display for MyError { | |
fn fmt(&self, f: &mut Formatter) -> FmtResult { | |
write!(f, "{}", to_string_pretty(self).unwrap()) | |
} | |
} | |
// we implement the ResponseError trait | |
impl ResponseError for MyError { | |
// builds the actual response to send back when an error occurs | |
fn error_response(&self) -> web::HttpResponse { | |
let err_json = json!({ "error": self.msg }); | |
web::HttpResponse::build(StatusCode::from_u16(self.status).unwrap()).json(err_json) | |
} | |
} | |
// structure for the correct response | |
#[derive(Serialize)] | |
struct MyResponse { | |
result: u32, | |
} | |
// handler than can answer an error or a correct json | |
#[get("/{id}")] | |
async fn index(web::Path(id): web::Path<u32>) -> Result<web::Json<MyResponse>, MyError> { | |
match id { | |
1 => Err(MyError { | |
msg: "an example error message".to_string(), | |
status: 400, | |
}), | |
id => Ok(web::Json(MyResponse { result: id })), | |
} | |
} | |
#[actix_web::main] | |
async fn main() -> io::Result<()> { | |
let ip_address = "127.0.0.1:8000"; | |
println!("Running server on {}", ip_address); | |
HttpServer::new(|| App::new().service(index)) | |
.bind(ip_address) | |
.expect("Can not bind to port 8000") | |
.run() | |
.await | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment