review tweaks

This commit is contained in:
Rob Ede 2021-06-05 18:15:08 +01:00
parent df25b43e67
commit 76ae9a0302
No known key found for this signature in database
GPG Key ID: 97C636207D3EF933
14 changed files with 110 additions and 138 deletions

View File

@ -10,8 +10,8 @@
* Update `language-tags` to `0.3`. * Update `language-tags` to `0.3`.
* `ServiceResponse::take_body`. [#2201] * `ServiceResponse::take_body`. [#2201]
* `ServiceResponse::map_body` closure receives and returns `B` instead of `ResponseBody<B>` types. [#2201] * `ServiceResponse::map_body` closure receives and returns `B` instead of `ResponseBody<B>` types. [#2201]
* All error trait bounds in server service builders have changed from `Into<Error>` to `Into<Response<AnyBody>>`. [#2224] * All error trait bounds in server service builders have changed from `Into<Error>` to `Into<Response<AnyBody>>`. [#2253]
* All error trait bounds in message body and stream impls changed from `Into<Error>` to `Into<Box<dyn std::error::Error>>`. [#2224] * All error trait bounds in message body and stream impls changed from `Into<Error>` to `Into<Box<dyn std::error::Error>>`. [#2253]
* `middleware::normalize` now will not try to normalize URIs with no valid path [#2246] * `middleware::normalize` now will not try to normalize URIs with no valid path [#2246]
### Removed ### Removed
@ -19,7 +19,7 @@
[#2200]: https://github.com/actix/actix-web/pull/2200 [#2200]: https://github.com/actix/actix-web/pull/2200
[#2201]: https://github.com/actix/actix-web/pull/2201 [#2201]: https://github.com/actix/actix-web/pull/2201
[#2224]: https://github.com/actix/actix-web/pull/2224 [#2253]: https://github.com/actix/actix-web/pull/2253
[#2246]: https://github.com/actix/actix-web/pull/2246 [#2246]: https://github.com/actix/actix-web/pull/2246

View File

@ -13,15 +13,15 @@
### Changed ### Changed
* The `MessageBody` trait now has an associated `Error` type. [#2183] * The `MessageBody` trait now has an associated `Error` type. [#2183]
* All error trait bounds in server service builders have changed from `Into<Error>` to `Into<Response<AnyBody>>`. [#2224] * All error trait bounds in server service builders have changed from `Into<Error>` to `Into<Response<AnyBody>>`. [#2253]
* All error trait bounds in message body and stream impls changed from `Into<Error>` to `Into<Box<dyn std::error::Error>>`. [#2224] * All error trait bounds in message body and stream impls changed from `Into<Error>` to `Into<Box<dyn std::error::Error>>`. [#2253]
* Places in `Response` where `ResponseBody<B>` was received or returned now simply use `B`. [#2201] * Places in `Response` where `ResponseBody<B>` was received or returned now simply use `B`. [#2201]
* `header` mod is now public. [#2171] * `header` mod is now public. [#2171]
* `uri` mod is now public. [#2171] * `uri` mod is now public. [#2171]
* Update `language-tags` to `0.3`. * Update `language-tags` to `0.3`.
* Reduce the level from `error` to `debug` for the log line that is emitted when a `500 Internal Server Error` is built using `HttpResponse::from_error`. [#2201] * Reduce the level from `error` to `debug` for the log line that is emitted when a `500 Internal Server Error` is built using `HttpResponse::from_error`. [#2201]
* `ResponseBuilder::message_body` now returns a `Result`. [#2201] * `ResponseBuilder::message_body` now returns a `Result`. [#2201]
* Remove `Unpin` bound on `ResponseBuilder::streaming`. [#2224] * Remove `Unpin` bound on `ResponseBuilder::streaming`. [#2253]
### Removed ### Removed
* Stop re-exporting `http` crate's `HeaderMap` types in addition to ours. [#2171] * Stop re-exporting `http` crate's `HeaderMap` types in addition to ours. [#2171]
@ -39,7 +39,7 @@
[#2201]: https://github.com/actix/actix-web/pull/2201 [#2201]: https://github.com/actix/actix-web/pull/2201
[#2205]: https://github.com/actix/actix-web/pull/2205 [#2205]: https://github.com/actix/actix-web/pull/2205
[#2215]: https://github.com/actix/actix-web/pull/2215 [#2215]: https://github.com/actix/actix-web/pull/2215
[#2224]: https://github.com/actix/actix-web/pull/2224 [#2253]: https://github.com/actix/actix-web/pull/2253
[#2244]: https://github.com/actix/actix-web/pull/2244 [#2244]: https://github.com/actix/actix-web/pull/2244

View File

@ -9,14 +9,11 @@ use bytes::{BufMut, BytesMut};
use crate::{ use crate::{
body::BodySize, body::BodySize,
config::ServiceConfig, config::ServiceConfig,
header::{map::Value, HeaderName}, header::{map::Value, HeaderMap, HeaderName},
helpers,
http::{
header::{CONNECTION, CONTENT_LENGTH, DATE, TRANSFER_ENCODING}, header::{CONNECTION, CONTENT_LENGTH, DATE, TRANSFER_ENCODING},
HeaderMap, StatusCode, Version, helpers,
},
message::{ConnectionType, RequestHeadType}, message::{ConnectionType, RequestHeadType},
response::Response, Response, StatusCode, Version,
}; };
const AVERAGE_HEADER_SIZE: usize = 30; const AVERAGE_HEADER_SIZE: usize = 30;

View File

@ -198,7 +198,6 @@ impl<B> Response<B> {
impl<B> fmt::Debug for Response<B> impl<B> fmt::Debug for Response<B>
where where
B: MessageBody, B: MessageBody,
B::Error: Into<Error>,
{ {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
let res = writeln!( let res = writeln!(

View File

@ -128,8 +128,7 @@ pub use self::sender::SendClientRequest;
/// An asynchronous HTTP and WebSocket client. /// An asynchronous HTTP and WebSocket client.
/// ///
/// ## Examples /// # Examples
///
/// ``` /// ```
/// use awc::Client; /// use awc::Client;
/// ///

75
src/error/error.rs Normal file
View File

@ -0,0 +1,75 @@
use std::{error::Error as StdError, fmt};
use actix_http::{body::AnyBody, Response};
use crate::{HttpResponse, ResponseError};
/// General purpose actix web error.
///
/// An actix web error is used to carry errors from `std::error`
/// through actix in a convenient way. It can be created through
/// converting errors with `into()`.
///
/// Whenever it is created from an external object a response error is created
/// for it that can be used to create an HTTP response from it this means that
/// if you have access to an actix `Error` you can always get a
/// `ResponseError` reference from it.
pub struct Error {
cause: Box<dyn ResponseError>,
}
impl Error {
/// Returns the reference to the underlying `ResponseError`.
pub fn as_response_error(&self) -> &dyn ResponseError {
self.cause.as_ref()
}
/// Similar to `as_response_error` but downcasts.
pub fn as_error<T: ResponseError + 'static>(&self) -> Option<&T> {
<dyn ResponseError>::downcast_ref(self.cause.as_ref())
}
/// TODO
pub fn error_response(&self) -> HttpResponse {
self.cause.error_response()
}
}
impl fmt::Display for Error {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
fmt::Display::fmt(&self.cause, f)
}
}
impl fmt::Debug for Error {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(f, "{:?}", &self.cause)
}
}
impl StdError for Error {
fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
None
}
}
impl From<std::convert::Infallible> for Error {
fn from(val: std::convert::Infallible) -> Self {
match val {}
}
}
/// `Error` for any error that implements `ResponseError`
impl<T: ResponseError + 'static> From<T> for Error {
fn from(err: T) -> Error {
Error {
cause: Box::new(err),
}
}
}
impl From<Error> for Response<AnyBody> {
fn from(err: Error) -> Response<AnyBody> {
err.error_response().into()
}
}

View File

@ -3,7 +3,7 @@ use std::{cell::RefCell, fmt, io::Write as _};
use actix_http::{body::Body, header, StatusCode}; use actix_http::{body::Body, header, StatusCode};
use bytes::{BufMut as _, BytesMut}; use bytes::{BufMut as _, BytesMut};
use crate::{Error, HttpResponse, ResponseError}; use crate::{Error, HttpRequest, HttpResponse, Responder, ResponseError};
/// Wraps errors to alter the generated response status code. /// Wraps errors to alter the generated response status code.
/// ///
@ -102,6 +102,15 @@ where
} }
} }
impl<T> Responder for InternalError<T>
where
T: fmt::Debug + fmt::Display + 'static,
{
fn respond_to(self, _: &HttpRequest) -> HttpResponse {
HttpResponse::from_error(self)
}
}
macro_rules! error_helper { macro_rules! error_helper {
($name:ident, $status:ident) => { ($name:ident, $status:ident) => {
paste::paste! { paste::paste! {

View File

@ -9,12 +9,15 @@ use url::ParseError as UrlParseError;
use crate::http::StatusCode; use crate::http::StatusCode;
#[allow(clippy::module_inception)]
mod error;
mod internal; mod internal;
mod macros; mod macros;
mod response_error; mod response_error;
pub use self::error::Error;
pub use self::internal::*; pub use self::internal::*;
pub use self::response_error::{Error, ResponseError}; pub use self::response_error::ResponseError;
/// A convenience [`Result`](std::result::Result) for Actix Web operations. /// A convenience [`Result`](std::result::Result) for Actix Web operations.
/// ///

View File

@ -12,90 +12,6 @@ use bytes::BytesMut;
use crate::{__downcast_dyn, __downcast_get_type_id}; use crate::{__downcast_dyn, __downcast_get_type_id};
use crate::{helpers, HttpResponse}; use crate::{helpers, HttpResponse};
/// General purpose actix web error.
///
/// An actix web error is used to carry errors from `std::error`
/// through actix in a convenient way. It can be created through
/// converting errors with `into()`.
///
/// Whenever it is created from an external object a response error is created
/// for it that can be used to create an HTTP response from it this means that
/// if you have access to an actix `Error` you can always get a
/// `ResponseError` reference from it.
pub struct Error {
cause: Box<dyn ResponseError>,
}
impl Error {
/// Returns the reference to the underlying `ResponseError`.
pub fn as_response_error(&self) -> &dyn ResponseError {
self.cause.as_ref()
}
/// Similar to `as_response_error` but downcasts.
pub fn as_error<T: ResponseError + 'static>(&self) -> Option<&T> {
<dyn ResponseError>::downcast_ref(self.cause.as_ref())
}
/// TODO
pub fn error_response(&self) -> HttpResponse {
self.cause.error_response()
}
}
impl fmt::Display for Error {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
fmt::Display::fmt(&self.cause, f)
}
}
impl fmt::Debug for Error {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(f, "{:?}", &self.cause)
}
}
impl StdError for Error {
fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
None
}
}
impl From<std::convert::Infallible> for Error {
fn from(val: std::convert::Infallible) -> Self {
match val {}
}
}
/// `Error` for any error that implements `ResponseError`
impl<T: ResponseError + 'static> From<T> for Error {
fn from(err: T) -> Error {
Error {
cause: Box::new(err),
}
}
}
impl From<Error> for Response<AnyBody> {
fn from(err: Error) -> Response<AnyBody> {
err.error_response().into()
}
}
/////////////////////
/////////////////////
/////////////////////
/////////////////////
/////////////////////
/////////////////////
/////////////////////
/////////////////////
/////////////////////
/////////////////////
/////////////////////
/////////////////////
/////////////////////
/// Errors that can generate responses. /// Errors that can generate responses.
// TODO: add std::error::Error bound when replacement for Box<dyn Error> is found // TODO: add std::error::Error bound when replacement for Box<dyn Error> is found
pub trait ResponseError: fmt::Debug + fmt::Display { pub trait ResponseError: fmt::Debug + fmt::Display {

View File

@ -47,8 +47,7 @@ pub trait FromRequest: Sized {
/// ///
/// If the FromRequest for T fails, return None rather than returning an error response /// If the FromRequest for T fails, return None rather than returning an error response
/// ///
/// ## Example /// # Examples
///
/// ``` /// ```
/// use actix_web::{web, dev, App, Error, HttpRequest, FromRequest}; /// use actix_web::{web, dev, App, Error, HttpRequest, FromRequest};
/// use actix_web::error::ErrorBadRequest; /// use actix_web::error::ErrorBadRequest;
@ -139,8 +138,7 @@ where
/// ///
/// If the `FromRequest` for T fails, inject Err into handler rather than returning an error response /// If the `FromRequest` for T fails, inject Err into handler rather than returning an error response
/// ///
/// ## Example /// # Examples
///
/// ``` /// ```
/// use actix_web::{web, dev, App, Result, Error, HttpRequest, FromRequest}; /// use actix_web::{web, dev, App, Result, Error, HttpRequest, FromRequest};
/// use actix_web::error::ErrorBadRequest; /// use actix_web::error::ErrorBadRequest;

View File

@ -1,7 +1,6 @@
//! Actix Web is a powerful, pragmatic, and extremely fast web framework for Rust. //! Actix Web is a powerful, pragmatic, and extremely fast web framework for Rust.
//! //!
//! ## Example //! # Examples
//!
//! ```no_run //! ```no_run
//! use actix_web::{get, web, App, HttpServer, Responder}; //! use actix_web::{get, web, App, HttpServer, Responder};
//! //!
@ -20,8 +19,7 @@
//! } //! }
//! ``` //! ```
//! //!
//! ## Documentation & Community Resources //! # Documentation & Community Resources
//!
//! In addition to this API documentation, several other resources are available: //! In addition to this API documentation, several other resources are available:
//! //!
//! * [Website & User Guide](https://actix.rs/) //! * [Website & User Guide](https://actix.rs/)
@ -44,8 +42,7 @@
//! structs represent HTTP requests and responses and expose methods for creating, inspecting, //! structs represent HTTP requests and responses and expose methods for creating, inspecting,
//! and otherwise utilizing them. //! and otherwise utilizing them.
//! //!
//! ## Features //! # Features
//!
//! * Supports *HTTP/1.x* and *HTTP/2* //! * Supports *HTTP/1.x* and *HTTP/2*
//! * Streaming and pipelining //! * Streaming and pipelining
//! * Keep-alive and slow requests handling //! * Keep-alive and slow requests handling
@ -59,8 +56,7 @@
//! * Includes an async [HTTP client](https://docs.rs/awc/) //! * Includes an async [HTTP client](https://docs.rs/awc/)
//! * Runs on stable Rust 1.46+ //! * Runs on stable Rust 1.46+
//! //!
//! ## Crate Features //! # Crate Features
//!
//! * `compress` - content encoding compression support (enabled by default) //! * `compress` - content encoding compression support (enabled by default)
//! * `cookies` - cookies support (enabled by default) //! * `cookies` - cookies support (enabled by default)
//! * `openssl` - HTTPS support via `openssl` crate, supports `HTTP/2` //! * `openssl` - HTTPS support via `openssl` crate, supports `HTTP/2`

View File

@ -356,8 +356,7 @@ impl Drop for HttpRequest {
/// It is possible to get `HttpRequest` as an extractor handler parameter /// It is possible to get `HttpRequest` as an extractor handler parameter
/// ///
/// ## Example /// # Examples
///
/// ``` /// ```
/// use actix_web::{web, App, HttpRequest}; /// use actix_web::{web, App, HttpRequest};
/// use serde_derive::Deserialize; /// use serde_derive::Deserialize;

View File

@ -1,4 +1,4 @@
use std::{borrow::Cow, fmt}; use std::borrow::Cow;
use actix_http::{ use actix_http::{
body::Body, body::Body,
@ -6,7 +6,7 @@ use actix_http::{
}; };
use bytes::{Bytes, BytesMut}; use bytes::{Bytes, BytesMut};
use crate::{error::InternalError, Error, HttpRequest, HttpResponse, HttpResponseBuilder}; use crate::{Error, HttpRequest, HttpResponse, HttpResponseBuilder};
/// Trait implemented by types that can be converted to an HTTP response. /// Trait implemented by types that can be converted to an HTTP response.
/// ///
@ -226,15 +226,6 @@ impl<T: Responder> Responder for CustomResponder<T> {
} }
} }
impl<T> Responder for InternalError<T>
where
T: fmt::Debug + fmt::Display + 'static,
{
fn respond_to(self, _: &HttpRequest) -> HttpResponse {
HttpResponse::from_error(self)
}
}
#[cfg(test)] #[cfg(test)]
pub(crate) mod tests { pub(crate) mod tests {
use actix_service::Service; use actix_service::Service;

View File

@ -22,10 +22,7 @@ use {
cookie::Cookie, cookie::Cookie,
}; };
use crate::{ use crate::{error::Error, HttpResponseBuilder};
error::{Error, ResponseError},
HttpResponseBuilder,
};
/// An HTTP Response /// An HTTP Response
pub struct HttpResponse<B = AnyBody> { pub struct HttpResponse<B = AnyBody> {
@ -54,12 +51,6 @@ impl HttpResponse<AnyBody> {
pub fn from_error(error: impl Into<Error>) -> Self { pub fn from_error(error: impl Into<Error>) -> Self {
error.into().as_response_error().error_response() error.into().as_response_error().error_response()
} }
/// Create an error response.
#[inline]
pub fn from_http_error(error: &dyn ResponseError) -> Self {
error.error_response()
}
} }
impl<B> HttpResponse<B> { impl<B> HttpResponse<B> {
@ -242,7 +233,6 @@ impl<B> HttpResponse<B> {
impl<B> fmt::Debug for HttpResponse<B> impl<B> fmt::Debug for HttpResponse<B>
where where
B: MessageBody, B: MessageBody,
B::Error: Into<actix_http::Error>,
{ {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.debug_struct("HttpResponse") f.debug_struct("HttpResponse")