From edde5085ebe7816f31d0e52ae71edf6f32bd1092 Mon Sep 17 00:00:00 2001 From: NerdyPepper Date: Tue, 19 Jun 2018 21:49:23 +0530 Subject: Handle errors nicely --- src/content.rs | 49 +++++++++++++++++++++++++++++++++++++++---------- 1 file changed, 39 insertions(+), 10 deletions(-) (limited to 'src') diff --git a/src/content.rs b/src/content.rs index 5be4206..19293d2 100644 --- a/src/content.rs +++ b/src/content.rs @@ -2,6 +2,8 @@ extern crate reqwest; extern crate serde_json; extern crate cursive; +use cursive::Cursive; +use cursive::views::Dialog; use serde_json::Value; use reqwest::Response; @@ -11,7 +13,7 @@ pub fn query_url_gen(title: &str) -> String { // query config let mut url = String::from("https://en.wikipedia.org"); - url.push_str("w/api.php?"); + url.push_str("/w/api.php?"); url.push_str("action=query&"); url.push_str("format=json&"); url.push_str("prop=extracts&"); @@ -29,7 +31,7 @@ pub fn search_url_gen(search: &str) -> String { search.replace(" ", "%20"); let mut url = String::from("https://en.wikipedia.org"); - url.push_str("w/api.php?"); + url.push_str("/w/api.php?"); url.push_str("action=opensearch&"); url.push_str("format=json&"); url.push_str("search="); @@ -41,21 +43,22 @@ pub fn search_url_gen(search: &str) -> String { } -pub fn get_extract(title: &str, mut res: reqwest::Response) -> String { - let mut v: Value = serde_json::from_str(&res.text().unwrap()).unwrap(); +pub fn get_extract(title: &str) -> Result { + let url = query_url_gen(title); + let res = reqwest::get(&url[..])?; - // Fetch page and pageids of requested title(s) + let mut v: Value = match serde_json::from_str(&res.text()?) { + Ok(x) => x, + Err(x) => , + }; let pageid = &v["query"]["pageids"][0]; let pageid_str = match pageid { Value::String(id) => id, _ => panic!("wut"), }; - if pageid_str == "-1" { - String::from("No such page") - } else { - format!("{}", &v["query"]["pages"][pageid_str]["extract"]) - } + Ok(format!("{}", &v["query"]["pages"][pageid_str]["extract"])) + } pub fn get_title(title: &str, mut res: Response) -> String { @@ -97,3 +100,29 @@ pub fn get_search_results(search: &str) -> Vec { } } + +pub fn pop_error(s: &mut Cursive, msg: &str) { + s.add_layer(Dialog::text("An error occurred\n:(") + .title("Oopsie woopsie") + .button("Ok", |s| s.quit())); +} + +fn handler(e: reqwest::Error) -> &str { + if e.is_http() { + match e.url() { + None => format!("No URL given"), + Some(url) => format!("Problem making request to: {}", url), + } + } + // Inspect the internal error and output it + if e.is_serialization() { + let serde_error = match e.get_ref() { + None => return, + Some(err) => err, + }; + format!("problem parsing information {}", serde_error) + + if e.is_redirect() { + format!("server redirecting too many times or making loop") + } +} -- cgit v1.2.3