Marcel Kopera
Marcel Kopera

Reputation: 314

Panic when can't create a directory

I'm writing a Rust program which will create a directory based on user input. I would like to know how to panic with my own text when error occurs, like Permission Error etc...

fn create_dir(path: &String) -> std::io::Result<()> {
    std::fs::create_dir_all(path)?;
    Ok(())
}

This will do nothing when error occcurs

Upvotes: 2

Views: 1618

Answers (2)

Jim D
Jim D

Reputation: 179

Here is what I came up with for a bit more robust and flexible error handling. I has a lot of println! The function will be for copying files, but at this point I am just creating the destination directory if it does not exist.

use std::{fs::{self, ReadDir}, path::{Path, PathBuf}};
fn main() {

    let src_path = PathBuf::from("C:/Dev");
    let dest_path = PathBuf::from("e:/yyyyyy");
    copy_folders(src_path, dest_path);
}

fn copy_folders(src: PathBuf, dest: PathBuf){
    if !src.is_dir() {
        println!("Path  is not a folder. Exiting function");
        return;
    }

    match dest.try_exists() {
        Err(error) => {println!("Error on folder.try_exists.  Error: {:?}", error.to_string());
                      panic!("I´m Outa Here!! - try_exists");
        },
        Ok(true) => {
            println!("Folder exists!!!");
            ()
        },
        Ok(false) => {
            match fs::create_dir(&dest) {
            Err(error) => {
                println!("Error creating dir.  Err: {}", error.to_string());
                panic!("I'm Outa Here!! - create_dir");
            },
            Ok(()) => println!("Created folder {:?}", dest.display())
         };}
    };
    println!("Folder name {:?}.  Folder root: {:?}", dest.file_name(), dest.display());
}

Upvotes: -1

Cerberus
Cerberus

Reputation: 10237

For this case, the simplest way is to use unwrap_or_else():

fn create_dir(path: &str) {
    std::fs::create_dir_all(path)
        .unwrap_or_else(|e| panic!("Error creating dir: {}", e));
}

Note that I also changed the argument type, for the reasons described here.


However, it would be more idiomatic to accept a &Path or AsRef<Path>.

use std::fs;
use std::path::Path;

fn create_dir<P: AsRef<Path>>(path: P) {
    fs::create_dir_all(path)
        .unwrap_or_else(|e| panic!("Error creating dir: {}", e));
}

Upvotes: 6

Related Questions