Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat: error handling #48

Merged
merged 14 commits into from
Oct 10, 2023
Merged
Show file tree
Hide file tree
Changes from 9 commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -4,3 +4,4 @@ members = [
"winapps-cli",
"winapps-gui",
]
resolver = "2"
18 changes: 11 additions & 7 deletions winapps-cli/src/main.rs
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
use clap::{arg, Command};
use winapps::freerdp::freerdp_back::Freerdp;
use winapps::quickemu::{create_vm, kill_vm, start_vm};
use winapps::RemoteClient;
use winapps::{unwrap_or_panic, RemoteClient};

fn cli() -> Command {
Command::new("winapps-cli")
Expand Down Expand Up @@ -69,18 +69,22 @@ fn main() {
}

Some((_, _)) => {
cli.about("Command not found, try existing ones!")
.print_help()
.expect("Couldn't print help");
unwrap_or_panic!(
cli.about("Command not found, try existing ones!")
.print_help(),
"Couldn't print help"
);
}
_ => unreachable!(),
};
}

Some((_, _)) => {
cli.about("Command not found, try existing ones!")
.print_help()
.expect("Couldn't print help");
unwrap_or_panic!(
cli.about("Command not found, try existing ones!")
.print_help(),
"Couldn't print help"
);
}
_ => unreachable!(),
}
Expand Down
4 changes: 1 addition & 3 deletions winapps-gui/src/main.rs
Original file line number Diff line number Diff line change
@@ -1,3 +1 @@
fn main() {
println!("Test lib: {}", winapps::add(1, 2));
}
fn main() {}
6 changes: 5 additions & 1 deletion winapps/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,11 @@ edition = "2021"
# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html

[dependencies]
anyhow = "1.0.75"
derive-new = "0.5.9"
home = "0.5.5"
lazy_static = "1.4.0"
serde = { version = "1.0.171", features = ["derive"] }
toml = "0.7.6"
thiserror = "1.0.49"
toml = "0.8.2"
tracing = "0.1.37"
143 changes: 143 additions & 0 deletions winapps/src/errors.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,143 @@
use std::error::Error;
use std::fmt::Debug;
use std::process::exit;

/// This enum represents all possible errors that can occur in this crate.
/// It is used as a return type for most functions should they return an error.
/// There's 2 base variants: `Message` and `WithError`.
/// `Message` is used for simple errors that don't have an underlying cause.
/// `WithError` is used for errors that occur from another error.
#[derive(thiserror::Error, Debug)]
pub enum WinappsError {
#[error("{0}")]
Message(String),
#[error("{0}\n{1}")]
WithError(#[source] anyhow::Error, String),
}

impl WinappsError {
/// This function prints the error to the console.
/// It is used internally by the `unrecoverable` and `panic` functions.
/// All lines are logged as seperate messages, and the source of the error is also logged if it exists.
fn error(&self) {
let messages: Vec<String> = self.to_string().split('\n').map(|s| s.into()).collect();
messages.iter().for_each(|s| tracing::error!("{}", s));

if self.source().is_some() {
tracing::error!("Caused by: {}", self.source().unwrap());
}
}

/// This function prints the error to the console and exits the program with an exit code of 1.
pub fn exit(&self) -> ! {
self.error();

tracing::error!("Unrecoverable error, exiting...");
exit(1);
}

/// This function prints the error to the console and panics.
pub fn panic(&self) -> ! {
self.error();

panic!("Program crashed, see log above");
}
}

/// This macro is a shortcut for creating a `WinappsError` from a string.
/// You can use normal `format!` syntax inside the macro.
#[macro_export]
macro_rules! error {
($($fmt:tt)*) => {
$crate::errors::WinappsError::Message(format!($($fmt)*))
};
}

/// This macro is a shortcut for creating a `WinappsError` from a string.
/// The first argument is the source error.
/// You can use normal `format!` syntax inside the macro.
#[macro_export]
macro_rules! error_from {
($err:expr, $($fmt:tt)*) => {
$crate::errors::WinappsError::WithError(anyhow::Error::new($err), format!($($fmt)*))
};
}

/// This trait serves as a generic way to convert a `Result` or `Option` into a `WinappsError`.
pub trait IntoError<T> {
fn into_error(self, msg: String) -> Result<T, WinappsError>;
}

impl<T, U> IntoError<T> for Result<T, U>
where
T: Debug,
U: Error + Send + Sync + 'static,
{
fn into_error(self, msg: String) -> Result<T, WinappsError> {
if let Err(error) = self {
return Err(WinappsError::WithError(anyhow::Error::new(error), msg));
}

Ok(self.unwrap())
}
}

impl<T> IntoError<T> for Option<T> {
fn into_error(self, msg: String) -> Result<T, WinappsError> {
if self.is_none() {
return Err(WinappsError::Message(msg));
}

Ok(self.unwrap())
}
}

/// This function unwraps a `Result` or `Option` and returns the value if it exists.
/// Should the value not exist, then the program will exit with an exit code of 1.
/// Called internally by the `unwrap_or_exit!` macro, which you should probably use instead.
pub fn unwrap_or_exit<T, U>(val: U, msg: String) -> T
where
T: Sized + Debug,
U: IntoError<T>,
{
val.into_error(msg).unwrap_or_else(|e| e.exit())
}

/// This function unwraps a `Result` or `Option` and returns the value if it exists.
/// Should the value not exist, then the program will panic.
/// Called internally by the `unwrap_or_panic!` macro, which you should probably use instead.
pub fn unwrap_or_panic<T, U>(val: U, msg: String) -> T
where
T: Sized + Debug,
U: IntoError<T>,
{
val.into_error(msg).unwrap_or_else(|e| e.panic())
}

/// This macro unwraps a `Result` or `Option` and returns the value if it exists.
/// Should the value not exist, then the program will exit with exit code 1.
/// Optionally, a message can be passed to the function which uses standard `format!` syntax.
/// The result type has to implement `Debug` and `Sized`, and the error type has to implement `Error`, `Send`, `Sync` has to be `'static`.
#[macro_export]
macro_rules! unwrap_or_exit {
($expr:expr) => {{
$crate::errors::unwrap_or_exit($expr, "Expected a value, got None / Error".into())
}};
($expr:expr, $($fmt:tt)*) => {{
$crate::errors::unwrap_or_exit($expr, format!($($fmt)*))
}};
}

/// This macro unwraps a `Result` or `Option` and returns the value if it exists.
/// Should the value not exist, then the program will panic.
/// Optionally, a message can be passed to the function which uses standard `format!` syntax.
/// The result type has to implement `Debug` and `Sized`, and the error type has to implement `Error`, `Send`, `Sync` has to be `'static`.
#[macro_export]
macro_rules! unwrap_or_panic {
($expr:expr) => {{
$crate::errors::unwrap_or_panic($expr, "Expected a value, got None / Error".into())
}};
($expr:expr, $($fmt:tt)*) => {{
$crate::errors::unwrap_or_panic($expr, format!($($fmt)*))
}};
}
28 changes: 18 additions & 10 deletions winapps/src/freerdp.rs
Original file line number Diff line number Diff line change
@@ -1,7 +1,8 @@
pub mod freerdp_back {
use std::process::{Command, Stdio};
use tracing::{info, warn};

use crate::{Config, RemoteClient};
use crate::{unwrap_or_exit, Config, RemoteClient};

pub struct Freerdp {}

Expand All @@ -11,18 +12,21 @@ pub mod freerdp_back {
xfreerdp.stdout(Stdio::null());
xfreerdp.stderr(Stdio::null());
xfreerdp.args(["-h"]);
xfreerdp
.spawn()
.expect("Freerdp execution failed! It needs to be installed!");
println!("Freerdp found!");

println!("All dependencies found!");
println!("Running explorer as test!");
println!("Check yourself if it appears correctly!");
unwrap_or_exit!(
xfreerdp.spawn(),
"Freerdp execution failed! It needs to be installed!",
);

info!("Freerdp found!");

info!("All dependencies found!");
info!("Running explorer as test!");
warn!("Check yourself if it appears correctly!");

self.run_app(config, Some(&"explorer.exe".to_string()));

println!("Test finished!");
info!("Test finished!");
}

fn run_app(&self, config: Config, app: Option<&String>) {
Expand Down Expand Up @@ -56,7 +60,11 @@ pub mod freerdp_back {
]);
}
}
xfreerdp.spawn().expect("Freerdp execution failed!");

unwrap_or_exit!(
xfreerdp.spawn(),
"Freerdp execution failed, check logs above!",
);
}
}
}
Loading