Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Switch to a concrete Error type #156

Closed
wants to merge 1 commit into from
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 2 additions & 0 deletions Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -26,6 +26,7 @@ http = "0.1.17"
log = { version = "0.4.7", features = ["kv_unstable"] }
mime = "0.3.13"
mime_guess = "2.0.3"
thiserror = "1.0"
serde = "1.0.97"
serde_json = "1.0.40"
serde_urlencoded = "0.6.1"
Expand Down Expand Up @@ -73,6 +74,7 @@ features = [
]

[dev-dependencies]
anyhow = "1.0"
async-std = { version = "1.0", features = ["attributes"] }
femme = "1.1.0"
serde = { version = "1.0.97", features = ["derive"] }
Expand Down
12 changes: 6 additions & 6 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -64,7 +64,7 @@ quick script, or a cross-platform SDK, Surf will make it work.
```rust
use async_std::task;

fn main() -> Result<(), Box<dyn std::error::Error + Send + Sync + 'static>> {
fn main() -> Result<(), surf::Error> {
task::block_on(async {
let mut res = surf::get("https://httpbin.org/get").await?;
dbg!(res.body_string().await?);
Expand All @@ -79,7 +79,7 @@ type directly.
```rust
use async_std::task;

fn main() -> Result<(), Box<dyn std::error::Error + Send + Sync + 'static>> {
fn main() -> Result<(), surf::Error> {
task::block_on(async {
dbg!(surf::get("https://httpbin.org/get").recv_string().await?);
Ok(())
Expand All @@ -93,7 +93,7 @@ Both sending and receiving JSON is real easy too.
use async_std::task;
use serde::{Deserialize, Serialize};

fn main() -> Result<(), Box<dyn std::error::Error + Send + Sync + 'static>> {
fn main() -> Result<(), surf::Error> {
#[derive(Deserialize, Serialize)]
struct Ip {
ip: String
Expand All @@ -118,7 +118,7 @@ And even creating streaming proxies is no trouble at all.
```rust
use async_std::task;

fn main() -> Result<(), Box<dyn std::error::Error + Send + Sync + 'static>> {
fn main() -> Result<(), surf::Error> {
task::block_on(async {
let reader = surf::get("https://img.fyi/q6YvNqP").await?;
let res = surf::post("https://box.rs/upload").body(reader).await?;
Expand All @@ -129,11 +129,11 @@ fn main() -> Result<(), Box<dyn std::error::Error + Send + Sync + 'static>> {

## Installation

Install OpenSSL -
Install OpenSSL -
- Ubuntu - ``` sudo apt install libssl-dev ```
- Fedora - ``` sudo dnf install openssl-devel ```

Make sure your rust is up to date using:
Make sure your rust is up to date using:
``` rustup update ```

With [cargo add](https://github.com/killercup/cargo-edit#Installation) installed :
Expand Down
4 changes: 2 additions & 2 deletions examples/hello_world.rs
Original file line number Diff line number Diff line change
Expand Up @@ -2,13 +2,13 @@ use async_std::task;

// The need for Ok with turbofish is explained here
// https://rust-lang.github.io/async-book/07_workarounds/03_err_in_async_blocks.html
fn main() -> Result<(), surf::Exception> {
fn main() -> anyhow::Result<()> {
femme::start(log::LevelFilter::Info)?;

task::block_on(async {
let uri = "https://httpbin.org/get";
let string: String = surf::get(uri).recv_string().await?;
println!("{}", string);
Ok::<(), surf::Exception>(())
Ok(())
})
}
7 changes: 4 additions & 3 deletions examples/middleware.rs
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
use async_std::task;
use futures::future::BoxFuture;
use surf::middleware::{HttpClient, Middleware, Next, Request, Response};
use surf::Result;

struct Printer;

Expand All @@ -10,7 +11,7 @@ impl<C: HttpClient> Middleware<C> for Printer {
req: Request,
client: C,
next: Next<'a, C>,
) -> BoxFuture<'a, Result<Response, surf::Exception>> {
) -> BoxFuture<'a, Result<Response>> {
Box::pin(async move {
println!("sending a request!");
let res = next.run(req, client).await?;
Expand All @@ -22,13 +23,13 @@ impl<C: HttpClient> Middleware<C> for Printer {

// The need for Ok with turbofish is explained here
// https://rust-lang.github.io/async-book/07_workarounds/03_err_in_async_blocks.html
fn main() -> Result<(), surf::Exception> {
fn main() -> anyhow::Result<()> {
femme::start(log::LevelFilter::Info)?;

task::block_on(async {
surf::get("https://httpbin.org/get")
.middleware(Printer {})
.await?;
Ok::<(), surf::Exception>(())
Ok(())
})
}
7 changes: 4 additions & 3 deletions examples/next_reuse.rs
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@ use async_std::task;
use futures::future::BoxFuture;
use futures::io::AsyncReadExt;
use surf::middleware::{Body, HttpClient, Middleware, Next, Request, Response};
use surf::Result;

struct Doubler;

Expand All @@ -11,7 +12,7 @@ impl<C: HttpClient> Middleware<C> for Doubler {
req: Request,
client: C,
next: Next<'a, C>,
) -> BoxFuture<'a, Result<Response, surf::Exception>> {
) -> BoxFuture<'a, Result<Response>> {
if req.method().is_safe() {
let mut new_req = Request::new(Body::empty());
*new_req.method_mut() = req.method().clone();
Expand Down Expand Up @@ -43,7 +44,7 @@ impl<C: HttpClient> Middleware<C> for Doubler {

// The need for Ok with turbofish is explained here
// https://rust-lang.github.io/async-book/07_workarounds/03_err_in_async_blocks.html
fn main() -> Result<(), surf::Exception> {
fn main() -> surf::Result<()> {
femme::start(log::LevelFilter::Info).unwrap();
task::block_on(async {
let mut res = surf::get("https://httpbin.org/get")
Expand All @@ -53,6 +54,6 @@ fn main() -> Result<(), surf::Exception> {
let body = res.body_bytes().await?;
let body = String::from_utf8_lossy(&body);
println!("{}", body);
Ok::<(), surf::Exception>(())
Ok(())
})
}
4 changes: 2 additions & 2 deletions examples/persistent.rs
Original file line number Diff line number Diff line change
Expand Up @@ -2,13 +2,13 @@ use async_std::task;

// The need for Ok with turbofish is explained here
// https://rust-lang.github.io/async-book/07_workarounds/03_err_in_async_blocks.html
fn main() -> Result<(), surf::Exception> {
fn main() -> surf::Result<()> {
femme::start(log::LevelFilter::Info).unwrap();
task::block_on(async {
let client = surf::Client::new();
let req1 = client.get("https://httpbin.org/get").recv_string();
let req2 = client.get("https://httpbin.org/get").recv_string();
futures::future::try_join(req1, req2).await?;
Ok::<(), surf::Exception>(())
Ok(())
})
}
4 changes: 2 additions & 2 deletions examples/post.rs
Original file line number Diff line number Diff line change
Expand Up @@ -2,13 +2,13 @@ use async_std::task;

// The need for Ok with turbofish is explained here
// https://rust-lang.github.io/async-book/07_workarounds/03_err_in_async_blocks.html
fn main() -> Result<(), surf::Exception> {
fn main() -> surf::Result<()> {
femme::start(log::LevelFilter::Info).unwrap();
task::block_on(async {
let uri = "https://httpbin.org/post";
let data = serde_json::json!({ "name": "chashu" });
let res = surf::post(uri).body_json(&data).unwrap().await?;
assert_eq!(res.status(), 200);
Ok::<(), surf::Exception>(())
Ok(())
})
}
22 changes: 11 additions & 11 deletions src/client.rs
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,7 @@ use http_client::native::NativeClient;
///
/// ```no_run
/// # #[async_std::main]
/// # async fn main() -> Result<(), Box<dyn std::error::Error + Send + Sync + 'static>> {
/// # async fn main() -> Result<(), surf::Error> {
/// let client = surf::Client::new();
/// let req1 = client.get("https://httpbin.org/get").recv_string();
/// let req2 = client.get("https://httpbin.org/get").recv_string();
Expand All @@ -30,7 +30,7 @@ impl Client<NativeClient> {
///
/// ```no_run
/// # #[async_std::main]
/// # async fn main() -> Result<(), Box<dyn std::error::Error + Send + Sync + 'static>> {
/// # async fn main() -> Result<(), surf::Error> {
/// let client = surf::Client::new();
/// # Ok(()) }
/// ```
Expand Down Expand Up @@ -63,7 +63,7 @@ impl<C: HttpClient> Client<C> {
///
/// ```no_run
/// # #[async_std::main]
/// # async fn main() -> Result<(), Box<dyn std::error::Error + Send + Sync + 'static>> {
/// # async fn main() -> Result<(), surf::Error> {
/// let client = surf::Client::new();
/// let string = client.get("https://httpbin.org/get").recv_string().await?;
/// # Ok(()) }
Expand All @@ -87,7 +87,7 @@ impl<C: HttpClient> Client<C> {
///
/// ```no_run
/// # #[async_std::main]
/// # async fn main() -> Result<(), Box<dyn std::error::Error + Send + Sync + 'static>> {
/// # async fn main() -> Result<(), surf::Error> {
/// let client = surf::Client::new();
/// let string = client.head("https://httpbin.org/head").recv_string().await?;
/// # Ok(()) }
Expand All @@ -111,7 +111,7 @@ impl<C: HttpClient> Client<C> {
///
/// ```no_run
/// # #[async_std::main]
/// # async fn main() -> Result<(), Box<dyn std::error::Error + Send + Sync + 'static>> {
/// # async fn main() -> Result<(), surf::Error> {
/// let client = surf::Client::new();
/// let string = client.post("https://httpbin.org/post").recv_string().await?;
/// # Ok(()) }
Expand All @@ -135,7 +135,7 @@ impl<C: HttpClient> Client<C> {
///
/// ```no_run
/// # #[async_std::main]
/// # async fn main() -> Result<(), Box<dyn std::error::Error + Send + Sync + 'static>> {
/// # async fn main() -> Result<(), surf::Error> {
/// let client = surf::Client::new();
/// let string = client.put("https://httpbin.org/put").recv_string().await?;
/// # Ok(()) }
Expand All @@ -159,7 +159,7 @@ impl<C: HttpClient> Client<C> {
///
/// ```no_run
/// # #[async_std::main]
/// # async fn main() -> Result<(), Box<dyn std::error::Error + Send + Sync + 'static>> {
/// # async fn main() -> Result<(), surf::Error> {
/// let client = surf::Client::new();
/// let string = client.delete("https://httpbin.org/delete").recv_string().await?;
/// # Ok(()) }
Expand All @@ -183,7 +183,7 @@ impl<C: HttpClient> Client<C> {
///
/// ```no_run
/// # #[async_std::main]
/// # async fn main() -> Result<(), Box<dyn std::error::Error + Send + Sync + 'static>> {
/// # async fn main() -> Result<(), surf::Error> {
/// let client = surf::Client::new();
/// let string = client.connect("https://httpbin.org/connect").recv_string().await?;
/// # Ok(()) }
Expand All @@ -207,7 +207,7 @@ impl<C: HttpClient> Client<C> {
///
/// ```no_run
/// # #[async_std::main]
/// # async fn main() -> Result<(), Box<dyn std::error::Error + Send + Sync + 'static>> {
/// # async fn main() -> Result<(), surf::Error> {
/// let client = surf::Client::new();
/// let string = client.options("https://httpbin.org/options").recv_string().await?;
/// # Ok(()) }
Expand All @@ -231,7 +231,7 @@ impl<C: HttpClient> Client<C> {
///
/// ```no_run
/// # #[async_std::main]
/// # async fn main() -> Result<(), Box<dyn std::error::Error + Send + Sync + 'static>> {
/// # async fn main() -> Result<(), surf::Error> {
/// let client = surf::Client::new();
/// let string = client.trace("https://httpbin.org/trace").recv_string().await?;
/// # Ok(()) }
Expand All @@ -255,7 +255,7 @@ impl<C: HttpClient> Client<C> {
///
/// ```no_run
/// # #[async_std::main]
/// # async fn main() -> Result<(), Box<dyn std::error::Error + Send + Sync + 'static>> {
/// # async fn main() -> Result<(), surf::Error> {
/// let client = surf::Client::new();
/// let string = client.patch("https://httpbin.org/patch").recv_string().await?;
/// # Ok(()) }
Expand Down
43 changes: 43 additions & 0 deletions src/error.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,43 @@
use std::result::Result as StdResult;

use thiserror::Error as ThisError;

#[allow(missing_docs)]
pub type Result<T> = StdResult<T, Error>;
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This already exists from the recent-ish ac215cb


#[allow(missing_docs)]
#[derive(ThisError, Debug)]
#[error(transparent)]
pub struct Error(#[from] InternalError);
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This probably doesn't need to exist. Ideally this would just using http_types::Error instead: https://docs.rs/http-types/2.3.0/http_types/struct.Error.html

(It's implemented like this: https://github.com/http-rs/http-types/blob/master/src/error.rs)


macro_rules! impl_from {
($bound:ty) => {
impl From<$bound> for Error {
fn from(err: $bound) -> Error {
InternalError::from(err).into()
}
}
};
}

impl_from!(log::kv::Error);
impl_from!(serde_urlencoded::ser::Error);
impl_from!(serde_urlencoded::de::Error);
impl_from!(std::io::Error);
impl_from!(serde_json::Error);

#[derive(ThisError, Debug)]
pub(crate) enum InternalError {
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Also with http_types::Error this shouldn't be necessary, because it wraps the errors and allows you to check downcasts, like so:

match surf::get(url).await {
    Ok() -> (),
    Err(error) -> {
        if let Some(&url_err) = error.downcast_ref::<UrlError>() {
            // ...
        } else if let Some(&json_err) = error.downcast_ref::<JsonError>() {
            // ...
        }
    }
}

#[error(transparent)]
LogError(#[from] log::kv::Error),
#[error(transparent)]
UrlEncodeError(#[from] serde_urlencoded::ser::Error),
#[error(transparent)]
UrlDecodeError(#[from] serde_urlencoded::de::Error),
#[error(transparent)]
IoError(#[from] std::io::Error),
#[error(transparent)]
JsonError(#[from] serde_json::Error),
#[error("{0}")]
HttpError(String),
}
13 changes: 6 additions & 7 deletions src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,7 @@
//! # Examples
//! ```no_run
//! # #[async_std::main]
//! # async fn main() -> Result<(), Box<dyn std::error::Error + Send + Sync + 'static>> {
//! # async fn main() -> Result<(), surf::Error> {
//! let mut res = surf::get("https://httpbin.org/get").await?;
//! dbg!(res.body_string().await?);
//! # Ok(()) }
Expand All @@ -24,7 +24,7 @@
//! It's also possible to skip the intermediate `Response`, and access the response type directly.
//! ```no_run
//! # #[async_std::main]
//! # async fn main() -> Result<(), Box<dyn std::error::Error + Send + Sync + 'static>> {
//! # async fn main() -> Result<(), surf::Error> {
//! dbg!(surf::get("https://httpbin.org/get").recv_string().await?);
//! # Ok(()) }
//! ```
Expand All @@ -33,7 +33,7 @@
//! ```no_run
//! # use serde::{Deserialize, Serialize};
//! # #[async_std::main]
//! # async fn main() -> Result<(), Box<dyn std::error::Error + Send + Sync + 'static>> {
//! # async fn main() -> Result<(), surf::Error> {
//! #[derive(Deserialize, Serialize)]
//! struct Ip {
//! ip: String
Expand All @@ -54,7 +54,7 @@
//!
//! ```no_run
//! # #[async_std::main]
//! # async fn main() -> Result<(), Box<dyn std::error::Error + Send + Sync + 'static>> {
//! # async fn main() -> Result<(), surf::Error> {
//! let reader = surf::get("https://img.fyi/q6YvNqP").await?;
//! let res = surf::post("https://box.rs/upload").body(reader).await?;
//! # Ok(()) }
Expand All @@ -75,6 +75,7 @@
#![cfg_attr(test, deny(warnings))]

mod client;
mod error;
mod request;
mod response;

Expand All @@ -86,13 +87,11 @@ pub use mime;
pub use url;

pub use client::Client;
pub use error::{Error, Result};
pub use request::Request;
pub use response::{DecodeError, Response};

#[cfg(feature = "native-client")]
mod one_off;
#[cfg(feature = "native-client")]
pub use one_off::{connect, delete, get, head, options, patch, post, put, trace};

/// A generic error type.
pub type Exception = Box<dyn std::error::Error + Send + Sync + 'static>;
Loading