cloudflare / pingora

A library for building fast, reliable and evolvable network services.
Apache License 2.0
20.21k stars 1.1k forks source link

pingora_core::Result implement trait `From<T>` #303

Closed futurist closed 1 day ago

futurist commented 6 days ago

What is the problem your feature solves, or the need it fulfills?

Use ? in upstream_peer:

async fn upstream_peer(
        &self,
        session: &mut Session,
        ctx: &mut Self::CTX,
    ) -> Result<Box<HttpPeer>>
{
  let mut req_counter = self.req_counter.lock()?;
}

The error is:

`?` couldn't convert the error to `Box<pingora_core::Error>`
the question mark operation (`?`) implicitly performs a conversion on the error value using the `From` trait
the following other types implement trait `From<T>`:
  <Box<(dyn ErrorTrait + 'a)> as From<&str>>
  <Box<(dyn ErrorTrait + 'a)> as From<Cow<'b, str>>>
  <Box<(dyn ErrorTrait + 'a)> as From<E>>
  <Box<(dyn ErrorTrait + 'a)> as From<std::string::String>>
  <Box<(dyn ErrorTrait + 'static)> as From<anyhow::Error>>
  <Box<(dyn ErrorTrait + std::marker::Send + 'static)> as From<anyhow::Error>>
  <Box<(dyn ErrorTrait + std::marker::Send + std::marker::Sync + 'a)> as From<&str>>
  <Box<(dyn ErrorTrait + std::marker::Send + std::marker::Sync + 'a)> as From<Cow<'b, str>>>
and 29 others

Describe the solution you'd like

Implement the trait From<T> for pingora_core::Result

Describe alternatives you've considered

Compatible with anyhow::Result?

drcaramelsyrup commented 5 days ago

Pingora has its own error types in order to attach metadata, which can help the framework do things like attribute the type or source of an error e.g. whether it was from upstream/downstream.

You may convert from a std Result and anyhow::Result using a trait method like err.explain_err(...) (to replace the error with a pingora type) or err.or_err(...) (to preserve the original error as the cause when logging, and wrap it in a pingora error). Check out the OrErr trait and the ErrorTypes.