Skip to content

Instantly share code, notes, and snippets.

@tom-curley
Created April 3, 2020 10:34
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save tom-curley/87bc877a7672fffb6ead41a4b851d205 to your computer and use it in GitHub Desktop.
Save tom-curley/87bc877a7672fffb6ead41a4b851d205 to your computer and use it in GitHub Desktop.
#[macro_use]
extern crate actix_web;
use failure::Fail;
use actix_web::{
http, middleware, web, App, HttpResponse,
HttpServer, error
};
use serde::{Deserialize, Serialize};
use std::env;
#[derive(Fail, Debug)]
enum WebError {
#[fail(display = "Invalid id '{}'", id)]
InvalidIdError { id: i32 },
#[fail(display = "Invalid request, please try again later")]
RandomInternalError,
}
impl error::ResponseError for WebError {
fn error_response(&self) -> HttpResponse {
match *self {
WebError::InvalidIdError{..} => HttpResponse::new(http::StatusCode::BAD_REQUEST),
WebError::RandomInternalError => HttpResponse::new(http::StatusCode::INTERNAL_SERVER_ERROR)
}
}
}
#[derive(Debug, Clone, Serialize, Deserialize)]
struct Bookmark {
id: i32,
url: String,
}
#[get("by-id/{id}")]
async fn bookmarks_by_id(id: web::Path<(i32)>) -> Result<HttpResponse, WebError> {
if *id < 10 {
Ok(HttpResponse::Ok().json(Bookmark{
id: *id,
url: "https://blog.x5dd.xyz".into(),
}))
}
else {
Err(WebError::InvalidIdError { id: *id })
}
}
#[actix_rt::main]
async fn main() -> std::io::Result<()> {
env::set_var("RUST_LOG", "actix_web=debug");
env_logger::init();
HttpServer::new(|| {
App::new()
.wrap(middleware::Logger::default())
.service(
web::scope("/bookmarks")
.service(bookmarks_by_id)
)
.route("/underconstruction",
web::get().to(|| async Result::<HttpResponse, WebError>::Err(WebError::RandomInternalError)),
)
})
.bind("127.0.0.1:8081")?
.run()
.await
}
@tom-curley
Copy link
Author

I am following a book on Rust and the source is available here:
https://github.com/PacktPublishing/Rust-Programming-Cookbook/tree/master/Chapter08/web-errors

I have noticed that the actin_web is outdated and I am trying to update the code with actin_web 2. However, I just can't get the example to compile

dependencies

actix-web = "2"
env_logger = "0.6"
actix-files = "0"
actix-rt = "1"
serde = { version = "1.0", features = ["derive"] }
failure = "0"

I am getting an error on line 62. I have also added the async keyword still no luck

web::get().to(|| async Result::<HttpResponse, WebError>::Err(WebError::RandomInternalError)),

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment