From 469d0994f16a5854bb8488c9024563041c560c5a Mon Sep 17 00:00:00 2001 From: Nazar <63452145+Tokarak@users.noreply.github.com> Date: Fri, 2 Feb 2024 19:53:15 +0000 Subject: [PATCH] Handle errors from reddit (#35) * Fix error handling logic A 401 code is still an Ok(<...>) response * Fix json key * Run `cargo fmt` --- src/client.rs | 25 ++++++++----------------- 1 file changed, 8 insertions(+), 17 deletions(-) diff --git a/src/client.rs b/src/client.rs index 781f88b4..7536b932 100644 --- a/src/client.rs +++ b/src/client.rs @@ -320,28 +320,19 @@ pub async fn json(path: String, quarantine: bool) -> Result { let json: Value = value; // If Reddit returned an error if json["error"].is_i64() { - Err( - json["reason"] - .as_str() - .unwrap_or_else(|| { - json["message"].as_str().unwrap_or_else(|| { - eprintln!("{REDDIT_URL_BASE}{path} - Error parsing reddit error"); - "Error parsing reddit error" - }) - }) - .to_string(), - ) + // OAuth token has expired; http status 401 + if json["message"] == "Unauthorized" { + error!("Forcing a token refresh"); + let () = force_refresh_token().await; + return Err("OAuth token has expired. Please refresh the page!".to_string()); + } + Err(format!("Reddit error {} \"{}\": {}", json["error"], json["reason"], json["message"])) } else { Ok(json) } } Err(e) => { - error!("Got a bad response from reddit {e}. Status code: {status}"); - // Unauthorized; token expired - if status == 401 { - error!("Forcing a token refresh"); - let () = force_refresh_token().await; - } + error!("Got an invalid response from reddit {e}. Status code: {status}"); if status.is_server_error() { Err("Reddit is having issues, check if there's an outage".to_string()) } else {