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

Better error handling and reporting #52

Open
Seeker14491 opened this issue Jul 28, 2022 · 1 comment
Open

Better error handling and reporting #52

Seeker14491 opened this issue Jul 28, 2022 · 1 comment
Labels
enhancement New feature or request TODO Will get to it!

Comments

@Seeker14491
Copy link
Contributor

Error handling could use a rework. There's many places in the Rust code where we call unwrap() for things like file system access or downloading stuff, which means Cultivation will crash if any of those operations fail. I think if such an operation fails, we should display that error on the frontend such as with a pop up message. The Rust code will need refactoring first though, so we return Results to the frontend instead of crashing.

@SpikeHD SpikeHD added enhancement New feature or request TODO Will get to it! labels Jul 28, 2022
@Seeker14491
Copy link
Contributor Author

I came up with a really simple way to handle errors on the Rust side: https://github.com/Seeker14491/anyhow-tauri. It's just a fork of the popular error handling library anyhow, but with a tiny tweak that lets you return its error type from Tauri commands. As an example, we can rewrite a function like this one in file_helpers.rs:

#[tauri::command]
pub fn read_file(path: String) -> String {
  let path_buf = std::path::PathBuf::from(&path);

  let mut file = match fs::File::open(path_buf) {
    Ok(file) => file,
    Err(e) => {
      println!("Failed to open file: {}", e);
      return String::new();
    }
  };

  let mut contents = String::new();
  file.read_to_string(&mut contents).unwrap();

  contents
}

into this:

#[tauri::command]
pub fn read_file(path: &Path) -> Result<String> {
  let mut file = File::open(path)?;
  let mut contents = String::new();
  file.read_to_string(&mut contents)?;

  Ok(contents)
}

without any other boilerplate. You can also attach context like in vanilla anyhow:

file.read_to_string(&mut contents).context("helpful error context goes here")?;

If the function errors, on the TypeScript side we can read the error and any context it might have. We can also optionally get a backtrace that shows where the error occurred, at least for debug builds.

Also, for file operations specifically, we can use the fs_err crate to get better error messages.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
enhancement New feature or request TODO Will get to it!
Projects
None yet
Development

No branches or pull requests

2 participants