improve error handling

This commit is contained in:
steven-omaha
2023-01-10 18:00:02 +01:00
parent 99bdced2a1
commit 122665a088
3 changed files with 28 additions and 8 deletions
+5 -4
View File
@@ -21,14 +21,15 @@ impl Backend for Rust {
impl_backend_constants!();
fn get_all_installed_packages(&self) -> Result<HashSet<Package>> {
let file = get_crates_file().unwrap();
let content = read_to_string(file).unwrap();
let json: Value = serde_json::from_str(&content).unwrap();
extract_packages(json)
let file = get_crates_file().context("getting path to crates file")?;
let content = read_to_string(file).context("reading crates file")?;
let json: Value = serde_json::from_str(&content).context("parsing JSON")?;
extract_packages(json).context("extracing packages from JSON")
}
fn get_explicitly_installed_packages(&self) -> Result<HashSet<Package>> {
self.get_all_installed_packages()
.context("getting all installed packages")
}
}
+19 -4
View File
@@ -4,8 +4,9 @@ use anyhow::{ensure, Context, Result};
use clap::ArgMatches;
use crate::action;
use crate::backend::{Backends, ToDoPerBackend};
use crate::backend::{Backend, Backends, ToDoPerBackend};
use crate::cmd::run_edit_command;
use crate::env::get_single_var;
use crate::ui::get_user_confirmation;
use crate::Group;
@@ -32,7 +33,9 @@ impl Pacdef {
Some((action::UNMANAGED, _)) => Ok(self.show_unmanaged_packages()),
Some((action::VERSION, _)) => Ok(self.show_version()),
Some((_, _)) => todo!(),
None => unreachable!(),
None => {
unreachable!("argument parser requires some subcommand to return an `ArgMatches`")
}
}
}
@@ -44,7 +47,7 @@ impl Pacdef {
match backend.get_missing_packages_sorted() {
Ok(diff) => to_install.push((backend, diff)),
Err(e) => println!("WARNING: skipping backend '{}': {e}", backend.get_section()),
Err(error) => show_error(error, backend),
};
}
@@ -123,7 +126,7 @@ impl Pacdef {
match backend.get_unmanaged_packages_sorted() {
Ok(unmanaged) => result.push((backend, unmanaged)),
Err(e) => println!("WARNING: skipping backend '{}': {e}", backend.get_section()),
Err(error) => show_error(error, backend),
};
}
result
@@ -165,3 +168,15 @@ impl Pacdef {
}
}
}
fn show_error(error: anyhow::Error, backend: Box<dyn Backend>) {
let section = backend.get_section();
match get_single_var("RUST_BACKTRACE") {
Some(s) => {
if s == "1" || s == "full" {
println!("WARNING: skipping backend '{section}': {error:?}\n");
}
}
None => println!("WARNING: skipping backend '{section}': {error}"),
}
}
+4
View File
@@ -9,3 +9,7 @@ pub(crate) fn get_editor() -> Result<String> {
fn check_vars_in_order(vars: &[&str]) -> Option<String> {
vars.iter().flat_map(|v| var(v).ok()).next()
}
pub(crate) fn get_single_var(variable: &str) -> Option<String> {
var(variable).ok()
}