From 8034594006f57cd97cc9459a6723bb6d07fb19da Mon Sep 17 00:00:00 2001 From: spikecodes <19519553+spikecodes@users.noreply.github.com> Date: Mon, 22 Feb 2021 16:43:32 -0800 Subject: [PATCH] Better subreddit error messages. Closes #131 --- src/subreddit.rs | 7 ++++++- src/utils.rs | 42 ++++++++++++++++++++++++++---------------- 2 files changed, 32 insertions(+), 17 deletions(-) diff --git a/src/subreddit.rs b/src/subreddit.rs index 9c05809..7cf0d5d 100644 --- a/src/subreddit.rs +++ b/src/subreddit.rs @@ -74,7 +74,12 @@ pub async fn page(req: Request<()>) -> tide::Result { prefs: prefs(req), }) } - Err(msg) => error(req, msg).await, + Err(msg) => match msg.as_str() { + "quarantined" => error(req, format!("r/{} has been quarantined by Reddit", sub)).await, + "private" => error(req, format!("r/{} is a private community", sub)).await, + "banned" => error(req, format!("r/{} has been banned from Reddit", sub)).await, + _ => error(req, msg).await, + }, } } diff --git a/src/utils.rs b/src/utils.rs index e1e0837..ac29d2e 100644 --- a/src/utils.rs +++ b/src/utils.rs @@ -4,7 +4,7 @@ use askama::Template; use cached::proc_macro::cached; use regex::Regex; -use serde_json::{from_str, Value}; +use serde_json::{from_str, Error, Value}; use std::collections::HashMap; use tide::{http::url::Url, http::Cookie, Request, Response}; use time::{Duration, OffsetDateTime}; @@ -514,29 +514,39 @@ pub async fn request(path: String) -> Result { let res = client.send(req).await; + let err = |msg: &str, e: String| -> Result { + println!("{} - {}: {}", url, msg, e); + Err(msg.to_string()) + }; + match res { Ok(mut response) => match response.take_body().into_string().await { // If response is success Ok(body) => { // Parse the response from Reddit as JSON - match from_str(&body) { - Ok(json) => Ok(json), - Err(e) => { - println!("{} - Failed to parse page JSON data: {}", url, e); - Err("Failed to parse page JSON data".to_string()) + let parsed: Result = from_str(&body); + match parsed { + Ok(json) => { + // If Reddit returned an error + if json["error"].is_i64() { + Err( + json["reason"] + .as_str() + .unwrap_or_else(|| { + println!("{} - Error parsing reddit error", url); + "Error parsing reddit error" + }) + .to_string(), + ) + } else { + Ok(json) + } } + Err(e) => err("Failed to parse page JSON data", e.to_string()), } } - // Failed to parse body - Err(e) => { - println!("{} - Couldn't parse request body: {}", url, e); - Err("Couldn't parse request body".to_string()) - } + Err(e) => err("Couldn't parse request body", e.to_string()), }, - // If failed to send request - Err(e) => { - println!("{} - Couldn't send request to Reddit: {}", url, e); - Err("Couldn't send request to Reddit".to_string()) - } + Err(e) => err("Couldn't send request to Reddit", e.to_string()), } }