1
0
mirror of https://github.com/fafhrd91/actix-web synced 2024-11-30 18:44:35 +01:00

added helper Task::error method

This commit is contained in:
Nikolay Kim 2017-11-25 10:52:43 -08:00
parent 45ecb87eab
commit 37c1e78c7a
4 changed files with 32 additions and 28 deletions

View File

@ -86,6 +86,16 @@ default impl<T: StdError + Sync + Send + 'static> ErrorResponse for T {
/// `InternalServerError` for `JsonError` /// `InternalServerError` for `JsonError`
impl ErrorResponse for JsonError {} impl ErrorResponse for JsonError {}
/// Return `InternalServerError` for `HttpError`,
/// Response generation can return `HttpError`, so it is internal error
impl ErrorResponse for HttpError {}
/// Return `InternalServerError` for `io::Error`
impl ErrorResponse for IoError {}
/// `InternalServerError` for `InvalidHeaderValue`
impl ErrorResponse for header::InvalidHeaderValue {}
/// Internal error /// Internal error
#[derive(Fail, Debug)] #[derive(Fail, Debug)]
#[fail(display="Unexpected task frame")] #[fail(display="Unexpected task frame")]
@ -191,13 +201,6 @@ impl From<IoError> for PayloadError {
} }
} }
/// Return `InternalServerError` for `HttpError`,
/// Response generation can return `HttpError`, so it is internal error
impl ErrorResponse for HttpError {}
/// Return `InternalServerError` for `io::Error`
impl ErrorResponse for IoError {}
/// Return `BadRequest` for `cookie::ParseError` /// Return `BadRequest` for `cookie::ParseError`
impl ErrorResponse for cookie::ParseError { impl ErrorResponse for cookie::ParseError {
fn error_response(&self) -> HttpResponse { fn error_response(&self) -> HttpResponse {

View File

@ -345,7 +345,7 @@ impl Start {
self.prepare(Task::reply(resp)), self.prepare(Task::reply(resp)),
Rc::clone(&self.middlewares))))) Rc::clone(&self.middlewares)))))
}, },
Started::Future(mut fut) => { Started::Future(fut) => {
self.fut = Some(fut); self.fut = Some(fut);
continue 'outer continue 'outer
}, },

View File

@ -1,7 +1,6 @@
//! Static files support. //! Static files support.
//! //!
//! TODO: needs to re-implement actual files handling, current impl blocks //! TODO: needs to re-implement actual files handling, current impl blocks
#![allow(dead_code, unused_variables)]
use std::io; use std::io;
use std::io::Read; use std::io::Read;
use std::rc::Rc; use std::rc::Rc;
@ -15,7 +14,7 @@ use payload::Payload;
use mime_guess::get_mime_type; use mime_guess::get_mime_type;
use httprequest::HttpRequest; use httprequest::HttpRequest;
use httpresponse::HttpResponse; use httpresponse::HttpResponse;
use httpcodes::{HTTPOk, HTTPNotFound, HTTPForbidden, HTTPInternalServerError}; use httpcodes::{HTTPOk, HTTPNotFound, HTTPForbidden};
/// Static files handling /// Static files handling
/// ///
@ -34,9 +33,9 @@ use httpcodes::{HTTPOk, HTTPNotFound, HTTPForbidden, HTTPInternalServerError};
pub struct StaticFiles { pub struct StaticFiles {
directory: PathBuf, directory: PathBuf,
accessible: bool, accessible: bool,
show_index: bool, _show_index: bool,
chunk_size: usize, _chunk_size: usize,
follow_symlinks: bool, _follow_symlinks: bool,
prefix: String, prefix: String,
} }
@ -66,9 +65,9 @@ impl StaticFiles {
StaticFiles { StaticFiles {
directory: dir, directory: dir,
accessible: access, accessible: access,
show_index: index, _show_index: index,
chunk_size: 0, _chunk_size: 0,
follow_symlinks: false, _follow_symlinks: false,
prefix: String::new(), prefix: String::new(),
} }
} }
@ -86,19 +85,19 @@ impl StaticFiles {
entry.path().strip_prefix(&self.directory).unwrap().to_string_lossy()); entry.path().strip_prefix(&self.directory).unwrap().to_string_lossy());
// if file is a directory, add '/' to the end of the name // if file is a directory, add '/' to the end of the name
let file_name = if let Ok(metadata) = entry.metadata() { if let Ok(metadata) = entry.metadata() {
if metadata.is_dir() { if metadata.is_dir() {
//format!("<li><a href=\"{}\">{}</a></li>", file_url, file_name)); //format!("<li><a href=\"{}\">{}</a></li>", file_url, file_name));
write!(body, "<li><a href=\"{}\">{}/</a></li>", let _ = write!(body, "<li><a href=\"{}\">{}/</a></li>",
file_url, entry.file_name().to_string_lossy()) file_url, entry.file_name().to_string_lossy());
} else { } else {
// write!(body, "{}/", entry.file_name()) // write!(body, "{}/", entry.file_name())
write!(body, "<li><a href=\"{}\">{}</a></li>", let _ = write!(body, "<li><a href=\"{}\">{}</a></li>",
file_url, entry.file_name().to_string_lossy()) file_url, entry.file_name().to_string_lossy());
} }
} else { } else {
continue continue
}; }
} }
} }
@ -139,7 +138,7 @@ impl<S: 'static> RouteHandler<S> for StaticFiles {
} }
} }
fn handle(&self, req: &mut HttpRequest, payload: Payload, state: Rc<S>) -> Task { fn handle(&self, req: &mut HttpRequest, _: Payload, _: Rc<S>) -> Task {
if !self.accessible { if !self.accessible {
Task::reply(HTTPNotFound) Task::reply(HTTPNotFound)
} else { } else {
@ -165,7 +164,7 @@ impl<S: 'static> RouteHandler<S> for StaticFiles {
Err(err) => return match err.kind() { Err(err) => return match err.kind() {
io::ErrorKind::NotFound => Task::reply(HTTPNotFound), io::ErrorKind::NotFound => Task::reply(HTTPNotFound),
io::ErrorKind::PermissionDenied => Task::reply(HTTPForbidden), io::ErrorKind::PermissionDenied => Task::reply(HTTPForbidden),
_ => Task::reply(HTTPInternalServerError), _ => Task::error(err),
} }
}; };
@ -175,7 +174,7 @@ impl<S: 'static> RouteHandler<S> for StaticFiles {
Err(err) => match err.kind() { Err(err) => match err.kind() {
io::ErrorKind::NotFound => Task::reply(HTTPNotFound), io::ErrorKind::NotFound => Task::reply(HTTPNotFound),
io::ErrorKind::PermissionDenied => Task::reply(HTTPForbidden), io::ErrorKind::PermissionDenied => Task::reply(HTTPForbidden),
_ => Task::reply(HTTPInternalServerError), _ => Task::error(err),
} }
} }
} else { } else {
@ -190,9 +189,7 @@ impl<S: 'static> RouteHandler<S> for StaticFiles {
let _ = file.read_to_end(&mut data); let _ = file.read_to_end(&mut data);
Task::reply(resp.body(data).unwrap()) Task::reply(resp.body(data).unwrap())
}, },
Err(err) => { Err(err) => Task::error(err),
Task::reply(HTTPInternalServerError)
}
} }
} }
} }

View File

@ -131,6 +131,10 @@ impl Task {
middlewares: None } middlewares: None }
} }
pub fn error<E: Into<Error>>(err: E) -> Self {
Task::reply(err.into())
}
pub(crate) fn with_context<C: IoContext>(ctx: C) -> Self { pub(crate) fn with_context<C: IoContext>(ctx: C) -> Self {
Task { state: TaskRunningState::Running, Task { state: TaskRunningState::Running,
iostate: TaskIOState::ReadingMessage, iostate: TaskIOState::ReadingMessage,