mirror of
https://github.com/actix/actix-extras.git
synced 2025-06-25 01:51:23 +02:00
make ErrorBadRequest type useful
This commit is contained in:
@ -4,6 +4,7 @@
|
||||
- [Getting Started](./qs_2.md)
|
||||
- [Application](./qs_3.md)
|
||||
- [Handler](./qs_4.md)
|
||||
- [Errors](./qs_4_5.md)
|
||||
- [State](./qs_6.md)
|
||||
- [Resources and Routes](./qs_5.md)
|
||||
- [Request & Response](./qs_7.md)
|
||||
|
@ -84,9 +84,7 @@ fn main() {
|
||||
.serve::<_, ()>("127.0.0.1:8088").unwrap();
|
||||
|
||||
println!("Started http server: 127.0.0.1:8088");
|
||||
// do not copy this line
|
||||
actix::Arbiter::system().send(actix::msgs::SystemExit(0));
|
||||
|
||||
# actix::Arbiter::system().send(actix::msgs::SystemExit(0));
|
||||
let _ = sys.run();
|
||||
}
|
||||
```
|
||||
|
@ -1,21 +1,19 @@
|
||||
# Handler
|
||||
|
||||
A request handler can by any object that implements
|
||||
[`Handler` trait](../actix_web/struct.HttpResponse.html#implementations).
|
||||
[`Handler` trait](../actix_web/dev/trait.Handler.html#implementors).
|
||||
Request handling happen in two stages. First handler object get called.
|
||||
Handle can return any object that implements
|
||||
[`FromRequest` trait](../actix_web/trait.FromRequest.html#foreign-impls).
|
||||
Then `from_request()` get called on returned object. And finally
|
||||
result of the `from_request()` call get converted to `Reply` object.
|
||||
|
||||
By default actix provdes several `Handler` implementations:
|
||||
|
||||
* Simple function that accepts `HttpRequest` and returns any object that
|
||||
implements `FromRequest` trait
|
||||
* Function that accepts `HttpRequest` and returns `Result<Reply, Into<Error>>` object.
|
||||
* Function that accepts `HttpRequest` and return actor that has `HttpContext<A>`as a context.
|
||||
|
||||
Actix provides response `FromRequest` implementation for some standard types,
|
||||
By default actix provides several `FromRequest` implementations for some standard types,
|
||||
like `&'static str`, `String`, etc.
|
||||
For complete list of implementations check
|
||||
[FromRequest documentation](../actix_web/trait.FromRequest.html#foreign-impls).
|
||||
|
||||
Examples:
|
||||
Examples of valid handlers:
|
||||
|
||||
```rust,ignore
|
||||
fn index(req: HttpRequest) -> &'static str {
|
||||
@ -41,9 +39,11 @@ fn index(req: HttpRequest) -> Box<Future<Item=HttpResponse, Error=Error>> {
|
||||
}
|
||||
```
|
||||
|
||||
## Custom conversion
|
||||
## Response with custom type
|
||||
|
||||
Let's create response for custom type that serializes to `application/json` response:
|
||||
To return custom type directly from handler function `FromResponse` trait should be
|
||||
implemented for this type. Let's create response for custom type that
|
||||
serializes to `application/json` response:
|
||||
|
||||
```rust
|
||||
# extern crate actix;
|
||||
@ -55,7 +55,7 @@ use actix_web::*;
|
||||
|
||||
#[derive(Serialize)]
|
||||
struct MyObj {
|
||||
name: String,
|
||||
name: &'static str,
|
||||
}
|
||||
|
||||
/// we have to convert Error into HttpResponse as well
|
||||
@ -73,18 +73,20 @@ impl FromRequest for MyObj {
|
||||
}
|
||||
}
|
||||
|
||||
fn index(req: HttpRequest) -> MyObj {
|
||||
MyObj{name: "user"}
|
||||
}
|
||||
|
||||
fn main() {
|
||||
let sys = actix::System::new("example");
|
||||
|
||||
HttpServer::new(
|
||||
Application::new("/")
|
||||
.resource("/", |r| r.method(
|
||||
Method::GET).f(|req| {MyObj{name: "user".to_owned()}})))
|
||||
.resource("/", |r| r.method(Method::GET).f(index)))
|
||||
.serve::<_, ()>("127.0.0.1:8088").unwrap();
|
||||
|
||||
println!("Started http server: 127.0.0.1:8088");
|
||||
actix::Arbiter::system().send(actix::msgs::SystemExit(0)); // <- remove this line, this code stops system during testing
|
||||
|
||||
# actix::Arbiter::system().send(actix::msgs::SystemExit(0));
|
||||
let _ = sys.run();
|
||||
}
|
||||
```
|
||||
|
135
guide/src/qs_4_5.md
Normal file
135
guide/src/qs_4_5.md
Normal file
@ -0,0 +1,135 @@
|
||||
# Errors
|
||||
|
||||
Actix uses [`Error` type](../actix_web/error/struct.Error.html)
|
||||
and [`ResponseError` trait](../actix_web/error/trait.ResponseError.html)
|
||||
for handling handler's errors.
|
||||
Any error that implements `ResponseError` trait can be returned as error value.
|
||||
*Handler* can return *Result* object, actix by default provides
|
||||
`FromRequest` implemenation for compatible result object. Here is implementation
|
||||
definition:
|
||||
|
||||
```rust,ignore
|
||||
impl<T: FromRequest, E: Into<Error>> FromRequest for Result<T, E>
|
||||
```
|
||||
|
||||
And any error that implements `ResponseError` can be converted into `Error` object.
|
||||
For example if *handler* function returns `io::Error`, it would be converted
|
||||
into `HTTPInternalServerError` response. Implementation for `io::Error` is provided
|
||||
by default.
|
||||
|
||||
```rust
|
||||
# extern crate actix_web;
|
||||
# use actix_web::*;
|
||||
use std::io;
|
||||
|
||||
fn index(req: HttpRequest) -> io::Result<fs::NamedFile> {
|
||||
Ok(fs::NamedFile::open("static/index.html")?)
|
||||
}
|
||||
#
|
||||
# fn main() {
|
||||
# Application::new("/")
|
||||
# .resource(r"/a/index.html", |r| r.f(index))
|
||||
# .finish();
|
||||
# }
|
||||
```
|
||||
|
||||
## Custom error response
|
||||
|
||||
To add support for custom errors all we need to do just implement `ResponseError` trait.
|
||||
`ResponseError` trait has default implementation for `error_response()` method, it
|
||||
generates *500* response.
|
||||
|
||||
```rust
|
||||
# extern crate actix_web;
|
||||
#[macro_use] extern crate failure;
|
||||
use actix_web::*;
|
||||
|
||||
#[derive(Fail, Debug)]
|
||||
#[fail(display="my error")]
|
||||
struct MyError {
|
||||
name: &'static str
|
||||
}
|
||||
|
||||
impl error::ResponseError for MyError {}
|
||||
|
||||
fn index(req: HttpRequest) -> Result<&'static str, MyError> {
|
||||
Err(MyError{name: "test"})
|
||||
}
|
||||
#
|
||||
# fn main() {
|
||||
# Application::new("/")
|
||||
# .resource(r"/a/index.html", |r| r.f(index))
|
||||
# .finish();
|
||||
# }
|
||||
```
|
||||
|
||||
In this example *index* handler will always return *500* response. But it is easy
|
||||
to return different responses.
|
||||
|
||||
```rust
|
||||
# extern crate actix_web;
|
||||
#[macro_use] extern crate failure;
|
||||
use actix_web::*;
|
||||
|
||||
#[derive(Fail, Debug)]
|
||||
enum MyError {
|
||||
#[fail(display="internal error")]
|
||||
InternalError,
|
||||
#[fail(display="bad request")]
|
||||
BadClientData,
|
||||
#[fail(display="timeout")]
|
||||
Timeout,
|
||||
}
|
||||
|
||||
impl error::ResponseError for MyError {
|
||||
fn error_response(&self) -> HttpResponse {
|
||||
match *self {
|
||||
MyError::InternalError => HttpResponse::new(
|
||||
StatusCode::INTERNAL_SERVER_ERROR, Body::Empty),
|
||||
MyError::BadClientData => HttpResponse::new(
|
||||
StatusCode::BAD_REQUEST, Body::Empty),
|
||||
MyError::Timeout => HttpResponse::new(
|
||||
StatusCode::GATEWAY_TIMEOUT, Body::Empty),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn index(req: HttpRequest) -> Result<&'static str, MyError> {
|
||||
Err(MyError::BadClientData)
|
||||
}
|
||||
#
|
||||
# fn main() {
|
||||
# Application::new("/")
|
||||
# .resource(r"/a/index.html", |r| r.f(index))
|
||||
# .finish();
|
||||
# }
|
||||
```
|
||||
|
||||
## Error helpers
|
||||
|
||||
Actix provides set of error helper types. It is possible to use them to generate
|
||||
specific error response. We can use helper types for first example with custom error.
|
||||
|
||||
```rust
|
||||
# extern crate actix_web;
|
||||
#[macro_use] extern crate failure;
|
||||
use actix_web::*;
|
||||
|
||||
#[derive(Debug)]
|
||||
struct MyError {
|
||||
name: &'static str
|
||||
}
|
||||
|
||||
fn index(req: HttpRequest) -> Result<&'static str> {
|
||||
let result: Result<&'static str, MyError> = Err(MyError{name: "test"});
|
||||
|
||||
Ok(result.map_err(error::ErrorBadRequest)?)
|
||||
}
|
||||
# fn main() {
|
||||
# Application::new("/")
|
||||
# .resource(r"/a/index.html", |r| r.f(index))
|
||||
# .finish();
|
||||
# }
|
||||
```
|
||||
|
||||
In this example *BAD REQUEST* response get generated for `MYError` error.
|
Reference in New Issue
Block a user