From be9502a5b8c05339548d7501090b1d5be8e0b832 Mon Sep 17 00:00:00 2001 From: Bilal Elmoussaoui Date: Mon, 6 Jun 2022 09:12:29 +0200 Subject: [PATCH] favicon-scrapper: Don't panic on error --- favicon-scrapper/src/error.rs | 8 ++++++++ favicon-scrapper/src/scrapper.rs | 10 ++++------ 2 files changed, 12 insertions(+), 6 deletions(-) diff --git a/favicon-scrapper/src/error.rs b/favicon-scrapper/src/error.rs index 7a35ef0..4f3d7db 100644 --- a/favicon-scrapper/src/error.rs +++ b/favicon-scrapper/src/error.rs @@ -5,6 +5,7 @@ pub enum Error { Io(std::io::Error), Image(image::ImageError), NoResults, + Utf8(std::str::Utf8Error), } impl From for Error { @@ -31,6 +32,12 @@ impl From for Error { } } +impl From for Error { + fn from(e: std::str::Utf8Error) -> Self { + Self::Utf8(e) + } +} + impl std::error::Error for Error {} impl std::fmt::Display for Error { @@ -41,6 +48,7 @@ impl std::fmt::Display for Error { Self::Url(e) => write!(f, "Url Parse Error{}", e), Self::Io(e) => write!(f, "IO Error {}", e), Self::Image(e) => write!(f, "Image Error {}", e), + Self::Utf8(e) => write!(f, "String conversion error {}", e), } } } diff --git a/favicon-scrapper/src/scrapper.rs b/favicon-scrapper/src/scrapper.rs index 3a35716..cc94165 100644 --- a/favicon-scrapper/src/scrapper.rs +++ b/favicon-scrapper/src/scrapper.rs @@ -33,7 +33,7 @@ impl Scrapper { #[allow(dead_code)] pub async fn from_file(path: PathBuf, base_url: Option) -> Result { let bytes = tokio::fs::read(path).await?; - let body = std::str::from_utf8(&bytes).unwrap(); + let body = std::str::from_utf8(&bytes)?; Self::from_string(body.to_owned(), base_url) } @@ -133,7 +133,7 @@ impl Scrapper { key: b"content", value, }) => { - let mut href = String::from_utf8(value.into_owned()).unwrap(); + let mut href = String::from_utf8(value.into_owned()).ok()?; if href.starts_with("//") { href = format!("https:{}", href); } @@ -178,7 +178,7 @@ impl Scrapper { key: b"href", value, }) => { - let mut href = String::from_utf8(value.into_owned()).unwrap(); + let mut href = String::from_utf8(value.into_owned()).ok()?; if href.starts_with("data:") { // only bitmap icons contain ';' as a separator, svgs uses ',' let mut icon_data = if href.contains(';') { @@ -233,9 +233,7 @@ impl Scrapper { key: b"sizes", value, }) => { - let size_inner = String::from_utf8(value.into_owned()) - .unwrap() - .to_lowercase(); + let size_inner = String::from_utf8(value.into_owned()).ok()?.to_lowercase(); let mut size_inner = size_inner.split('x'); let width = size_inner.next().and_then(|w| w.parse::().ok()); let height = size_inner.next().and_then(|h| h.parse::().ok());