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

[BUG] ParseError is not exported from url crate when implementing From<ParseError> for CustomError #380

Open
1 task done
sengho66 opened this issue Aug 27, 2023 · 0 comments

Comments

@sengho66
Copy link

Is there an existing issue for this?

  • I have searched the existing issues

What version of workers-rs are you using?

0.0.18

What version of wrangler are you using?

3.5.1

Describe the bug

When using Fetch::url, we first need to have the Url ready before we can use it.

async fn fetch_price(ticker_1: &str, ticker_2: &str) -> Result<Response, CustomError> {
    let path = format!(
        "{ENDPOINT}?symbol={}{}",
        ticker_1.to_uppercase(),
        ticker_2.to_uppercase()
    );

    let url_ = Url::parse(&path);
    // rest code
}

By calling Url::parse it returns a Result<Url, ParseError>, so we need to do a match.

    match url_ {
        Ok(url) => {
            let response = Fetch::Url(url).send().await?;
            return Ok(response);
        }
        Err(_) => Err(CustomError::new("Failed to parse.".into(), 404u16)),
    }

The above could be simplified if url::ParseError is exported along with url::Url.

    let url_ = Url::parse(&path)?;

But the above will not compile, it says the trait From<url::parser::ParseError> is not implemented for CustomError, now this should end because even if I implemented From<ParseError> for CustomError, ParseError is not exported.

We can fix this by exporting ParseError in:
https://github.com/cloudflare/workers-rs/blob/main/worker/src/lib.rs line 11

pub use url::{ParseError, Url};

Now this works!

#[derive(Debug)]
struct CustomError {
    status: u16,
    message: String,
}

impl From<ParseError> for CustomError {
    fn from(value: ParseError) -> Self {
        Self {
            status: 404u16,
            message: value.to_string(),
        }
    }
}

async fn fetch_price(ticker_1: &str, ticker_2: &str) -> Result<Response, CustomError> {
    let path = format!(
        "{ENDPOINT}?symbol={}{}",
        ticker_1.to_uppercase(),
        ticker_2.to_uppercase()
    );

    let url_ = Url::parse(&path)?;
    let response = Fetch::Url(url_).send().await?;
    return Ok(response);
}

Solution:

Since url::Url is re-exported, url::ParseError should be exported too.

Steps To Reproduce

No response

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant