From 96c3e504f866b2a06b2bfe724a18b61f25dc2a39 Mon Sep 17 00:00:00 2001 From: mxve <68632137+mxve@users.noreply.github.com> Date: Mon, 2 Oct 2023 04:39:49 +0200 Subject: [PATCH] improve logging of http errors --- src/http.rs | 54 ++++++++++++++++++++++++++++++++++++++++------------- src/misc.rs | 8 ++++++++ 2 files changed, 49 insertions(+), 13 deletions(-) diff --git a/src/http.rs b/src/http.rs index bec9408..63d97af 100644 --- a/src/http.rs +++ b/src/http.rs @@ -1,20 +1,35 @@ +use crate::misc; use std::{fs, io::Write, path::Path, str}; pub fn get_body(url: &str) -> Vec { let mut res: Vec = Vec::new(); - let req = http_req::request::Request::new(&url.try_into().unwrap()) + + match http_req::request::Request::new(&url.try_into().unwrap()) .header( "User-Agent", "AlterWare Launcher | github.com/mxve/alterware-launcher", ) .send(&mut res) - .unwrap_or_else(|error| { - panic!("\n\n{}:\n{:?}", "Error", error); - }); + { + Ok(req) => { + if req.status_code() == http_req::response::StatusCode::new(302) + || req.status_code() == http_req::response::StatusCode::new(301) + { + let location = req.headers().get("Location").unwrap().as_str(); + return get_body(location); + } - if req.status_code() == http_req::response::StatusCode::new(302) { - let location = req.headers().get("Location").unwrap().as_str(); - return get_body(location); + if req.status_code() != http_req::response::StatusCode::new(200) { + misc::fatal_error(&format!( + "Could not get body from {}, got {}", + url, + req.status_code() + )); + } + } + Err(e) => { + misc::fatal_error(&format!("Could not get body from {}, got:\n{}", url, e)); + } } res @@ -27,10 +42,23 @@ pub fn get_body_string(url: &str) -> String { pub fn download_file(url: &str, file_path: &Path) { let body = get_body(url); - let mut f = fs::File::create(file_path).unwrap_or_else(|error| { - panic!("\n\n{}:\n{:?}", "Error", error); - }); - f.write_all(&body).unwrap_or_else(|error| { - panic!("\n\n{}:\n{:?}", "Error", error); - }); + match fs::File::create(file_path) { + Ok(mut file) => match file.write_all(&body) { + Ok(_) => (), + Err(e) => { + misc::fatal_error(&format!( + "Could not write to file {}, got:\n{}", + file_path.to_str().unwrap(), + e + )); + } + }, + Err(e) => { + misc::fatal_error(&format!( + "Could not create file {}, got:\n{}", + file_path.to_str().unwrap(), + e + )); + } + } } diff --git a/src/misc.rs b/src/misc.rs index 78fab2c..28af4fc 100644 --- a/src/misc.rs +++ b/src/misc.rs @@ -1,5 +1,7 @@ use std::{fs, path::PathBuf}; +use colored::Colorize; + pub fn get_file_sha1(path: &PathBuf) -> String { let mut sha1 = sha1_smol::Sha1::new(); sha1.update(&fs::read(path).unwrap()); @@ -18,3 +20,9 @@ pub fn rev_to_int(rev: &str) -> u16 { .parse::() .unwrap_or(0) } + +pub fn fatal_error(error: &str) { + println!("\n\n{}:\n{}", "Error".bright_red(), error); + stdin(); + std::process::exit(1); +}