Skip to content

Commit

Permalink
refactor ResponseError trait
Browse files Browse the repository at this point in the history
  • Loading branch information
fafhrd91 committed Nov 26, 2019
1 parent 4dc31aa commit f73f973
Show file tree
Hide file tree
Showing 11 changed files with 105 additions and 111 deletions.
50 changes: 26 additions & 24 deletions MIGRATION.md
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,8 @@

replace `fn` with `async fn` to convert sync handler to async

* `TestServer::new()` renamed to `TestServer::start()`


## 1.0.1

Expand Down Expand Up @@ -41,52 +43,52 @@
* Extractor configuration. In version 1.0 this is handled with the new `Data` mechanism for both setting and retrieving the configuration

instead of

```rust

#[derive(Default)]
struct ExtractorConfig {
config: String,
}

impl FromRequest for YourExtractor {
type Config = ExtractorConfig;
type Result = Result<YourExtractor, Error>;

fn from_request(req: &HttpRequest, cfg: &Self::Config) -> Self::Result {
println!("use the config: {:?}", cfg.config);
...
}
}

App::new().resource("/route_with_config", |r| {
r.post().with_config(handler_fn, |cfg| {
cfg.0.config = "test".to_string();
})
})

```

use the HttpRequest to get the configuration like any other `Data` with `req.app_data::<C>()` and set it with the `data()` method on the `resource`

```rust
#[derive(Default)]
struct ExtractorConfig {
config: String,
}

impl FromRequest for YourExtractor {
type Error = Error;
type Future = Result<Self, Self::Error>;
type Config = ExtractorConfig;

fn from_request(req: &HttpRequest, payload: &mut Payload) -> Self::Future {
let cfg = req.app_data::<ExtractorConfig>();
println!("config data?: {:?}", cfg.unwrap().role);
...
}
}

App::new().service(
resource("/route_with_config")
.data(ExtractorConfig {
Expand All @@ -95,7 +97,7 @@
.route(post().to(handler_fn)),
)
```

* Resource registration. 1.0 version uses generalized resource
registration via `.service()` method.

Expand Down Expand Up @@ -386,9 +388,9 @@

* `HttpRequest` does not implement `Stream` anymore. If you need to read request payload
use `HttpMessage::payload()` method.

instead of

```rust
fn index(req: HttpRequest) -> impl Responder {
req
Expand All @@ -414,8 +416,8 @@
trait uses `&HttpRequest` instead of `&mut HttpRequest`.

* Removed `Route::with2()` and `Route::with3()` use tuple of extractors instead.
instead of

instead of

```rust
fn index(query: Query<..>, info: Json<MyStruct) -> impl Responder {}
Expand All @@ -431,7 +433,7 @@

* `Handler::handle()` accepts reference to `HttpRequest<_>` instead of value

* Removed deprecated `HttpServer::threads()`, use
* Removed deprecated `HttpServer::threads()`, use
[HttpServer::workers()](https://actix.rs/actix-web/actix_web/server/struct.HttpServer.html#method.workers) instead.

* Renamed `client::ClientConnectorError::Connector` to
Expand All @@ -440,7 +442,7 @@
* `Route::with()` does not return `ExtractorConfig`, to configure
extractor use `Route::with_config()`

instead of
instead of

```rust
fn main() {
Expand All @@ -451,11 +453,11 @@
});
}
```
use

use

```rust

fn main() {
let app = App::new().resource("/index.html", |r| {
r.method(http::Method::GET)
Expand Down Expand Up @@ -485,12 +487,12 @@
* `HttpRequest::extensions()` returns read only reference to the request's Extension
`HttpRequest::extensions_mut()` returns mutable reference.

* Instead of
* Instead of

`use actix_web::middleware::{
CookieSessionBackend, CookieSessionError, RequestSession,
Session, SessionBackend, SessionImpl, SessionStorage};`

use `actix_web::middleware::session`

`use actix_web::middleware::session{CookieSessionBackend, CookieSessionError,
Expand Down
7 changes: 3 additions & 4 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -26,16 +26,15 @@ Actix web is a simple, pragmatic and extremely fast web framework for Rust.
## Example

```rust
use actix_web::{web, App, HttpServer, Responder};
use actix_web::{get, App, HttpServer, Responder};

#[get("/{id}/{name}/index.html")]
async fn index(info: web::Path<(u32, String)>) -> impl Responder {
format!("Hello {}! id:{}", info.1, info.0)
}

fn main() -> std::io::Result<()> {
HttpServer::new(
|| App::new().service(
web::resource("/{id}/{name}/index.html").to(index)))
HttpServer::new(|| App::new().service(index))
.bind("127.0.0.1:8080")?
.run()
}
Expand Down
4 changes: 4 additions & 0 deletions actix-cors/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -93,6 +93,10 @@ pub enum CorsError {
}

impl ResponseError for CorsError {
fn status_code(&self) -> StatusCode {
StatusCode::BAD_REQUEST
}

fn error_response(&self) -> HttpResponse {
HttpResponse::with_body(StatusCode::BAD_REQUEST, format!("{}", self).into())
}
Expand Down
4 changes: 2 additions & 2 deletions actix-files/src/error.rs
Original file line number Diff line number Diff line change
Expand Up @@ -35,7 +35,7 @@ pub enum UriSegmentError {

/// Return `BadRequest` for `UriSegmentError`
impl ResponseError for UriSegmentError {
fn error_response(&self) -> HttpResponse {
HttpResponse::new(StatusCode::BAD_REQUEST)
fn status_code(&self) -> StatusCode {
StatusCode::BAD_REQUEST
}
}
12 changes: 5 additions & 7 deletions actix-http/src/client/error.rs
Original file line number Diff line number Diff line change
Expand Up @@ -7,8 +7,7 @@ use trust_dns_resolver::error::ResolveError;
use open_ssl::ssl::{Error as SslError, HandshakeError};

use crate::error::{Error, ParseError, ResponseError};
use crate::http::Error as HttpError;
use crate::response::Response;
use crate::http::{Error as HttpError, StatusCode};

/// A set of errors that can occur while connecting to an HTTP host
#[derive(Debug, Display, From)]
Expand Down Expand Up @@ -117,15 +116,14 @@ pub enum SendRequestError {

/// Convert `SendRequestError` to a server `Response`
impl ResponseError for SendRequestError {
fn error_response(&self) -> Response {
fn status_code(&self) -> StatusCode {
match *self {
SendRequestError::Connect(ConnectError::Timeout) => {
Response::GatewayTimeout()
StatusCode::GATEWAY_TIMEOUT
}
SendRequestError::Connect(_) => Response::BadGateway(),
_ => Response::InternalServerError(),
SendRequestError::Connect(_) => StatusCode::BAD_REQUEST,
_ => StatusCode::INTERNAL_SERVER_ERROR,
}
.into()
}
}

Expand Down
Loading

0 comments on commit f73f973

Please sign in to comment.