diff --git a/actix-http/CHANGES.md b/actix-http/CHANGES.md index 742ff8d3e..049f5328c 100644 --- a/actix-http/CHANGES.md +++ b/actix-http/CHANGES.md @@ -6,6 +6,8 @@ * Export IntoHeaderValue +* Render error and return as response body + ### Deleted * Removed PayloadBuffer diff --git a/actix-http/src/error.rs b/actix-http/src/error.rs index 45bf067dc..6098421a8 100644 --- a/actix-http/src/error.rs +++ b/actix-http/src/error.rs @@ -18,8 +18,6 @@ use tokio_timer::Error as TimerError; // re-export for convinience pub use crate::cookie::ParseError as CookieParseError; - -use crate::body::Body; use crate::response::Response; /// 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 { 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` diff --git a/actix-http/src/response.rs b/actix-http/src/response.rs index f82945526..ff0ce48de 100644 --- a/actix-http/src/response.rs +++ b/actix-http/src/response.rs @@ -1,7 +1,7 @@ //! Http response use std::cell::{Ref, RefMut}; use std::io::Write; -use std::{fmt, str}; +use std::{fmt, io, str}; use bytes::{BufMut, Bytes, BytesMut}; use futures::future::{ok, FutureResult, IntoFuture}; @@ -54,10 +54,13 @@ impl Response
{ /// Constructs an error response #[inline] pub fn from_error(error: Error) -> Response { - let resp = error.as_response_error().error_response(); - let mut resp = resp.set_body(Body::from(format!("{}", error))); + let mut resp = error.as_response_error().error_response(); + 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 + resp.set_body(Body::from(buf)) } /// 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