Skip to content

Commit

Permalink
chore(core): renaming Error::Normal to Error::Boxed
Browse files Browse the repository at this point in the history
  • Loading branch information
fundon committed Dec 14, 2023
1 parent ce037d1 commit 1be512f
Show file tree
Hide file tree
Showing 20 changed files with 167 additions and 141 deletions.
4 changes: 2 additions & 2 deletions examples/htmlx/src/main.rs
Original file line number Diff line number Diff line change
Expand Up @@ -52,7 +52,7 @@ async fn index(req: Request) -> Result<Response> {
"todos": todos
}),
)
.map_err(Error::normal)?;
.map_err(Error::boxed)?;
Ok(Response::html(body))
}

Expand All @@ -70,7 +70,7 @@ async fn list(req: Request) -> Result<Response> {
"todos": todos
}),
)
.map_err(Error::normal)?;
.map_err(Error::boxed)?;
Ok(Response::html(body))
}

Expand Down
2 changes: 1 addition & 1 deletion examples/otel/metrics/src/main.rs
Original file line number Diff line number Diff line change
Expand Up @@ -32,7 +32,7 @@ async fn main() -> Result<()> {
ExporterBuilder::default()
.with_registry(registry.clone())
.build()
.map_err(Error::normal)?,
.map_err(Error::boxed)?,
metrics::new_view(
Instrument::new().name("http.server.duration"),
Stream::new().aggregation(Aggregation::ExplicitBucketHistogram {
Expand Down
2 changes: 1 addition & 1 deletion examples/routing/openapi/src/main.rs
Original file line number Diff line number Diff line change
Expand Up @@ -284,7 +284,7 @@ async fn swagger_ui(req: Request) -> Result<Response> {
.map_err(|err| (StatusCode::INTERNAL_SERVER_ERROR, err.to_string()).into_error())?
{
Some(file) => Ok({
let content_type = HeaderValue::from_str(&file.content_type).map_err(Error::normal)?;
let content_type = HeaderValue::from_str(&file.content_type).map_err(Error::boxed)?;

let mut resp = Response::new(Full::from(file.bytes).into());
resp.headers_mut()
Expand Down
4 changes: 2 additions & 2 deletions examples/sse/src/main.rs
Original file line number Diff line number Diff line change
Expand Up @@ -39,8 +39,8 @@ async fn stats(req: Request) -> Result<impl IntoResponse> {
IntervalStream::new(interval(Duration::from_secs(10))).map(move |_| {
match sys
.load_average()
.map_err(Error::normal)
.and_then(|loadavg| serde_json::to_string(&loadavg).map_err(Error::normal))
.map_err(Error::boxed)
.and_then(|loadavg| serde_json::to_string(&loadavg).map_err(Error::boxed))
{
Ok(loadavg) => Event::default().data(loadavg),
Err(err) => {
Expand Down
2 changes: 1 addition & 1 deletion examples/templates/askama/src/main.rs
Original file line number Diff line number Diff line change
Expand Up @@ -18,7 +18,7 @@ async fn index(_: Request) -> Result<Response> {
buf.extend(
HelloTemplate { name: "world" }
.render()
.map_err(Error::normal)?
.map_err(Error::boxed)?
.as_bytes(),
);

Expand Down
4 changes: 2 additions & 2 deletions examples/templates/minijinja/src/main.rs
Original file line number Diff line number Diff line change
Expand Up @@ -26,7 +26,7 @@ async fn index(_: Request) -> Result<Response> {
let mut buf = BytesMut::with_capacity(512);
buf.extend(
TPLS.get_template("index.html")
.map_err(Error::normal)?
.map_err(Error::boxed)?
.render(context! {
title => "Viz.rs",
users => &vec![
Expand All @@ -40,7 +40,7 @@ async fn index(_: Request) -> Result<Response> {
},
],
})
.map_err(Error::normal)?
.map_err(Error::boxed)?
.as_bytes(),
);

Expand Down
2 changes: 1 addition & 1 deletion examples/templates/tera/src/main.rs
Original file line number Diff line number Diff line change
Expand Up @@ -37,7 +37,7 @@ async fn index(_: Request) -> Result<Response> {
let mut buf = BytesMut::with_capacity(512);
buf.extend(
TPLS.render("index.html", &ctx)
.map_err(Error::normal)?
.map_err(Error::boxed)?
.as_bytes(),
);

Expand Down
34 changes: 20 additions & 14 deletions viz-core/src/body.rs
Original file line number Diff line number Diff line change
Expand Up @@ -53,8 +53,8 @@ impl Body for IncomingBody {
Self::Empty => Poll::Ready(None),
Self::Incoming(i) => match i {
None => Poll::Ready(None),
Some(b) => match Pin::new(b).poll_frame(cx)? {
Poll::Ready(Some(f)) => Poll::Ready(Some(Ok(f))),
Some(inner) => match Pin::new(inner).poll_frame(cx)? {
Poll::Ready(Some(frame)) => Poll::Ready(Some(Ok(frame))),
Poll::Ready(None) => {
// the body has been used.
*i = None;
Expand All @@ -66,13 +66,15 @@ impl Body for IncomingBody {
}
}

#[inline]
fn is_end_stream(&self) -> bool {
match self {
Self::Empty | Self::Incoming(None) => true,
Self::Incoming(Some(inner)) => inner.is_end_stream(),
}
}

#[inline]
fn size_hint(&self) -> SizeHint {
match self {
Self::Empty | Self::Incoming(None) => SizeHint::with_exact(0),
Expand All @@ -84,11 +86,12 @@ impl Body for IncomingBody {
impl Stream for IncomingBody {
type Item = Result<Bytes, Box<dyn std::error::Error + Send + Sync + 'static>>;

#[inline]
fn poll_next(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Option<Self::Item>> {
match self.get_mut() {
Self::Empty | Self::Incoming(None) => Poll::Ready(None),
Self::Incoming(Some(inner)) => match Pin::new(inner).poll_frame(cx)? {
Poll::Ready(Some(f)) => Poll::Ready(f.into_data().map(Ok).ok()),
Poll::Ready(Some(frame)) => Poll::Ready(frame.into_data().map(Ok).ok()),
Poll::Ready(None) => Poll::Ready(None),
Poll::Pending => Poll::Pending,
},
Expand Down Expand Up @@ -160,42 +163,45 @@ impl Body for OutgoingBody {
) -> Poll<Option<Result<Frame<Self::Data>, Self::Error>>> {
match self.get_mut() {
Self::Empty => Poll::Ready(None),
Self::Full(f) => Pin::new(f).poll_frame(cx).map_err(Error::from),
Self::Boxed(b) => Pin::new(b).poll_frame(cx),
Self::Full(full) => Pin::new(full).poll_frame(cx).map_err(Error::from),
Self::Boxed(body) => Pin::new(body).poll_frame(cx),
}
}

#[inline]
fn is_end_stream(&self) -> bool {
match self {
Self::Empty => true,
Self::Full(f) => f.is_end_stream(),
Self::Boxed(b) => b.is_end_stream(),
Self::Full(full) => full.is_end_stream(),
Self::Boxed(body) => body.is_end_stream(),
}
}

#[inline]
fn size_hint(&self) -> SizeHint {
match self {
Self::Empty => SizeHint::with_exact(0),
Self::Full(f) => f.size_hint(),
Self::Boxed(b) => b.size_hint(),
Self::Full(full) => full.size_hint(),
Self::Boxed(body) => body.size_hint(),
}
}
}

impl Stream for OutgoingBody {
type Item = Result<Bytes, std::io::Error>;

#[inline]
fn poll_next(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Option<Self::Item>> {
match match self.get_mut() {
Self::Empty => return Poll::Ready(None),
Self::Full(f) => Pin::new(f)
Self::Full(full) => Pin::new(full)
.poll_frame(cx)
.map_err(|e| std::io::Error::new(std::io::ErrorKind::Other, e))?,
Self::Boxed(b) => Pin::new(b)
Self::Boxed(body) => Pin::new(body)
.poll_frame(cx)
.map_err(|e| std::io::Error::new(std::io::ErrorKind::Other, e))?,
} {
Poll::Ready(Some(f)) => Poll::Ready(f.into_data().map(Ok).ok()),
Poll::Ready(Some(frame)) => Poll::Ready(frame.into_data().map(Ok).ok()),
Poll::Ready(None) => Poll::Ready(None),
Poll::Pending => Poll::Pending,
}
Expand All @@ -205,8 +211,8 @@ impl Stream for OutgoingBody {
fn size_hint(&self) -> (usize, Option<usize>) {
let sh = match self {
Self::Empty => return (0, Some(0)),
Self::Full(f) => f.size_hint(),
Self::Boxed(b) => b.size_hint(),
Self::Full(full) => full.size_hint(),
Self::Boxed(body) => body.size_hint(),
};
(
usize::try_from(sh.lower()).unwrap_or(usize::MAX),
Expand Down
37 changes: 20 additions & 17 deletions viz-core/src/error.rs
Original file line number Diff line number Diff line change
Expand Up @@ -2,27 +2,30 @@ use std::error::Error as StdError;

use crate::{IntoResponse, Response, StatusCode, ThisError};

/// An owned dynamically typed [`StdError`].
pub type BoxError = Box<dyn StdError + Send + Sync>;

/// Represents errors that can occur handling application.
#[derive(ThisError, Debug)]
pub enum Error {
/// Receives a [`Response`] as error.
/// Receives a [`Response`] as an error.
#[error("response")]
Responder(Response),
/// Receives a boxed [`std::error::Error`][StdError] as error.
/// Receives a boxed [`std::error::Error`][StdError] as an error.
#[error(transparent)]
Normal(Box<dyn StdError + Send + Sync>),
/// Receives a boxed [`std::error::Error`][StdError] and [`Response`] pair as error.
Boxed(BoxError),
/// Receives a boxed [`std::error::Error`][StdError] and [`Response`] pair as an error.
#[error("report")]
Report(Box<dyn StdError + Send + Sync>, Response),
Report(BoxError, Response),
}

impl Error {
/// Create a new error object from any error type.
pub fn normal<T>(t: T) -> Self
pub fn boxed<T>(t: T) -> Self
where
T: StdError + Send + Sync + 'static,
{
Self::Normal(Box::new(t))
Self::Boxed(Box::new(t))
}

/// Forwards to the method defined on the type `dyn Error`.
Expand All @@ -32,7 +35,7 @@ impl Error {
T: StdError + 'static,
{
match self {
Self::Normal(e) | Self::Report(e, _) => e.is::<T>(),
Self::Boxed(e) | Self::Report(e, _) => e.is::<T>(),
Self::Responder(_) => false,
}
}
Expand All @@ -47,10 +50,10 @@ impl Error {
where
T: StdError + 'static,
{
if let Self::Normal(e) = self {
if let Self::Boxed(e) = self {
return match e.downcast::<T>() {
Ok(e) => Ok(*e),
Err(e) => Err(Self::Normal(e)),
Err(e) => Err(Self::Boxed(e)),
};
}
if let Self::Report(e, r) = self {
Expand All @@ -68,7 +71,7 @@ impl Error {
where
T: StdError + 'static,
{
if let Self::Normal(e) = self {
if let Self::Boxed(e) = self {
return e.downcast_ref::<T>();
}
if let Self::Report(e, _) = self {
Expand All @@ -83,7 +86,7 @@ impl Error {
where
T: StdError + 'static,
{
if let Self::Normal(e) = self {
if let Self::Boxed(e) = self {
return e.downcast_mut::<T>();
}
if let Self::Report(e, _) = self {
Expand Down Expand Up @@ -117,18 +120,18 @@ impl From<hyper::Error> for Error {

impl From<std::convert::Infallible> for Error {
fn from(e: std::convert::Infallible) -> Self {
Self::normal(e)
Self::boxed(e)
}
}

impl From<std::io::Error> for Error {
fn from(e: std::io::Error) -> Self {
Self::normal(e)
Self::boxed(e)
}
}

impl From<Box<dyn StdError + Send + Sync>> for Error {
fn from(value: Box<dyn StdError + Send + Sync>) -> Self {
Self::Normal(value)
impl From<BoxError> for Error {
fn from(value: BoxError) -> Self {
Self::Boxed(value)
}
}
50 changes: 32 additions & 18 deletions viz-core/src/handler.rs
Original file line number Diff line number Diff line change
Expand Up @@ -3,37 +3,51 @@
use crate::{async_trait, Future};

mod after;
mod and_then;
mod around;
mod before;
mod boxed;
mod catch_error;
mod catch_unwind;
mod either;
mod fn_ext;
mod fn_ext_hanlder;
mod into_handler;
mod map;
mod map_err;
mod map_into_response;
mod or_else;
mod transform;

pub use after::After;

mod and_then;
pub use and_then::AndThen;

mod around;
pub use around::{Around, Next};

mod before;
pub use before::Before;

mod boxed;
pub use boxed::BoxHandler;

mod catch_error;
pub use catch_error::CatchError;

mod catch_unwind;
pub use catch_unwind::CatchUnwind;

mod either;
pub use either::Either;

mod fn_ext;
pub use fn_ext::FnExt;

mod fn_ext_hanlder;
pub use fn_ext_hanlder::FnExtHandler;

mod into_handler;
pub use into_handler::IntoHandler;

mod map;
pub use map::Map;

mod map_err;
pub use map_err::MapErr;

mod map_into_response;
pub use map_into_response::MapInToResponse;

mod or_else;
pub use or_else::OrElse;

mod transform;
pub use transform::Transform;

/// A simplified asynchronous interface for handling input and output.
Expand All @@ -48,8 +62,6 @@ pub trait Handler<Input>: dyn_clone::DynClone + Send + Sync + 'static {
async fn call(&self, input: Input) -> Self::Output;
}

impl<I, T: ?Sized> HandlerExt<I> for T where T: Handler<I> {}

#[async_trait]
impl<F, I, Fut, O> Handler<I> for F
where
Expand Down Expand Up @@ -180,3 +192,5 @@ pub trait HandlerExt<I>: Handler<I> {
f(self)
}
}

impl<I, T: ?Sized> HandlerExt<I> for T where T: Handler<I> {}
2 changes: 1 addition & 1 deletion viz-core/src/into_response.rs
Original file line number Diff line number Diff line change
Expand Up @@ -26,7 +26,7 @@ impl IntoResponse for Response {
impl IntoResponse for Error {
fn into_response(self) -> Response {
match self {
Error::Normal(error) => {
Error::Boxed(error) => {
let body = error.to_string();
Response::builder()
.status(StatusCode::INTERNAL_SERVER_ERROR)
Expand Down
Loading

0 comments on commit 1be512f

Please sign in to comment.