1
0
mirror of https://github.com/fafhrd91/actix-web synced 2025-01-18 13:51:50 +01:00

Render error and return as response body

This commit is contained in:
Nikolay Kim 2019-04-03 19:55:19 -07:00
parent 954fe21751
commit 1e2bd68e83
5 changed files with 27 additions and 22 deletions

View File

@ -6,6 +6,8 @@
* Export IntoHeaderValue * Export IntoHeaderValue
* Render error and return as response body
### Deleted ### Deleted
* Removed PayloadBuffer * Removed PayloadBuffer

View File

@ -18,8 +18,6 @@ use tokio_timer::Error as TimerError;
// re-export for convinience // re-export for convinience
pub use crate::cookie::ParseError as CookieParseError; pub use crate::cookie::ParseError as CookieParseError;
use crate::body::Body;
use crate::response::Response; use crate::response::Response;
/// A specialized [`Result`](https://doc.rust-lang.org/std/result/enum.Result.html) /// A specialized [`Result`](https://doc.rust-lang.org/std/result/enum.Result.html)
@ -49,13 +47,6 @@ impl Error {
pub fn as_response_error(&self) -> &ResponseError { pub fn as_response_error(&self) -> &ResponseError {
self.cause.as_ref() self.cause.as_ref()
} }
/// Converts error to a response instance and set error message as response body
pub fn response_with_message(self) -> Response {
let message = format!("{}", self);
let resp: Response = self.into();
resp.set_body(Body::from(message))
}
} }
/// Error that can be converted to `Response` /// Error that can be converted to `Response`

View File

@ -1,7 +1,7 @@
//! Http response //! Http response
use std::cell::{Ref, RefMut}; use std::cell::{Ref, RefMut};
use std::io::Write; use std::io::Write;
use std::{fmt, str}; use std::{fmt, io, str};
use bytes::{BufMut, Bytes, BytesMut}; use bytes::{BufMut, Bytes, BytesMut};
use futures::future::{ok, FutureResult, IntoFuture}; use futures::future::{ok, FutureResult, IntoFuture};
@ -54,10 +54,13 @@ impl Response<Body> {
/// Constructs an error response /// Constructs an error response
#[inline] #[inline]
pub fn from_error(error: Error) -> Response { pub fn from_error(error: Error) -> Response {
let resp = error.as_response_error().error_response(); let mut resp = error.as_response_error().error_response();
let mut resp = resp.set_body(Body::from(format!("{}", error))); let mut buf = BytesMut::new();
let _ = write!(Writer(&mut buf), "{}", error);
resp.headers_mut()
.insert(header::CONTENT_TYPE, HeaderValue::from_static("text/plain"));
resp.error = Some(error); resp.error = Some(error);
resp resp.set_body(Body::from(buf))
} }
/// Convert response to response with body /// Convert response to response with body
@ -300,6 +303,18 @@ impl<'a> Iterator for CookieIter<'a> {
} }
} }
pub struct Writer<'a>(pub &'a mut BytesMut);
impl<'a> io::Write for Writer<'a> {
fn write(&mut self, buf: &[u8]) -> io::Result<usize> {
self.0.extend_from_slice(buf);
Ok(buf.len())
}
fn flush(&mut self) -> io::Result<()> {
Ok(())
}
}
/// An HTTP response builder /// An HTTP response builder
/// ///
/// This type can be used to construct an instance of `Response` through a /// This type can be used to construct an instance of `Response` through a

View File

@ -867,7 +867,7 @@ fn test_h1_response_http_error_handling() {
// read response // read response
let bytes = srv.load_body(response).unwrap(); let bytes = srv.load_body(response).unwrap();
assert!(bytes.is_empty()); assert_eq!(bytes, Bytes::from_static(b"failed to parse header value"));
} }
#[cfg(feature = "ssl")] #[cfg(feature = "ssl")]
@ -900,7 +900,7 @@ fn test_h2_response_http_error_handling() {
// read response // read response
let bytes = srv.load_body(response).unwrap(); let bytes = srv.load_body(response).unwrap();
assert!(bytes.is_empty()); assert_eq!(bytes, Bytes::from_static(b"failed to parse header value"));
} }
#[test] #[test]

View File

@ -417,12 +417,7 @@ impl FormatText {
)) ))
}; };
} }
FormatText::UrlPath => { FormatText::UrlPath => *self = FormatText::Str(format!("{}", req.path())),
*self = FormatText::Str(format!(
"{}",
req.path()
))
}
FormatText::RequestTime => { FormatText::RequestTime => {
*self = FormatText::Str(format!( *self = FormatText::Str(format!(
"{:?}", "{:?}",
@ -489,7 +484,9 @@ mod tests {
let req = TestRequest::with_header( let req = TestRequest::with_header(
header::USER_AGENT, header::USER_AGENT,
header::HeaderValue::from_static("ACTIX-WEB"), header::HeaderValue::from_static("ACTIX-WEB"),
).uri("/test/route/yeah").to_srv_request(); )
.uri("/test/route/yeah")
.to_srv_request();
let now = time::now(); let now = time::now();
for unit in &mut format.0 { for unit in &mut format.0 {