Handling Potential Errors

The library can fail if the environment is weird. Here's how to catch and handle those errors.

The BaseDir::new() and BaseDir::global() functions don’t just return a BaseDir struct. They return a Result<BaseDir, xdgdir::Error>. This is because things can go wrong if the user’s environment isn’t set up correctly.

In my previous examples, I used .unwrap() to keep things simple, but in a real app, you should handle these potential errors. This guide shows you what those errors are and how to deal with them.

The Kinds of Errors

There are two ways that xdgdir can fail.

  1. Error::HomeNotSet This is the most common error. It happens if the $HOME environment variable is not set or is an empty string. The XDG spec needs $HOME to figure out the default paths, so if it’s missing, the library can’t continue.
  2. Error::NotAbsolutePath(key, path) This error happens if $HOME or one of the XDG_* variables contains a relative path (like some/dir) instead of an absolute one (like /home/user/some/dir). The spec says these paths must be absolute. This error is helpful because it tells you exactly which variable (key) had the invalid path.

How to Handle the Errors

The best way to handle these errors is with a match statement. This lets you react differently to each kind of error and give the user a useful message.

Here’s a complete example that shows how to handle both cases.

Rust
use xdgdir::{BaseDir, Error};

fn main() {
    let result = BaseDir::new("my-app");

    match result {
        Ok(dirs) => {
            println!("Config directory: {}", dirs.config.display());
            // You can safely use the dirs struct here
        }
        Err(e) => {
            eprintln!("Error finding XDG directories:");
            match e {
                Error::HomeNotSet => {
                    eprintln!("The $HOME environment variable is not set.");
                }
                Error::NotAbsolutePath(key, path) => {
                    eprintln!(
                        "The path for ${} is not an absolute path: {}",
                        key,
                        path.display()
                    );
                }
            }
            // Exit with an error code
            std::process::exit(1);
        }
    }
}

By checking for these errors, you make your application more reliable. You can’t control what your user’s environment looks like, so it’s always a good idea to handle cases where it might be misconfigured.