Oxeon / Examples / Error handling

Error handling

Result, Option, the ? operator, custom error enums and panics in Oxeon, where a panic stops only the mod.

Partly works today

Option, Result, their methods, ? and panic! compile today. Closures work with them too, as in ok_or_else and map_err. Not yet: &str, String, slices, Display and assert!. ? doesn’t convert errors with From yet, so both sides need the same error type.

Errors are values, as in Rust. A function that can fail returns Result<T, E>, and a value that may be missing is an Option<T>. Both are ordinary generic enums, defined in Oxeon in a small prelude that’s compiled with every mod.

? returns early: on an Err or None it returns that from the function, and otherwise it unwraps the value.

A custom error type is usually an enum, and implementing Display describes it for people.

panic! and failed assertions trap the mod. The game disables that one mod and keeps running, so a bug in a mod can’t take the game down.

07_error_handling.ox

examples/syntax/07_error_handling.ox
// Result, Option and `?`. A panic traps the mod; the game keeps running.

#[derive(Debug)]
pub enum ConfigError {
    Missing(String),
    Invalid { key: String, value: String },
}

impl core::fmt::Display for ConfigError {
    fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
        match self {
            ConfigError::Missing(key) => write!(f, "missing key `{key}`"),
            ConfigError::Invalid { key, value } => write!(f, "bad value `{value}` for `{key}`"),
        }
    }
}

fn parse_speed(raw: Option<&str>) -> Result<f32, ConfigError> {
    let raw = raw.ok_or_else(|| ConfigError::Missing("speed".into()))?;
    raw.parse::<f32>().map_err(|_| ConfigError::Invalid {
        key: "speed".into(),
        value: raw.into(),
    })
}

fn double_speed(raw: Option<&str>) -> Result<f32, ConfigError> {
    let speed = parse_speed(raw)?; // early-returns the error
    Ok(speed * 2.0)
}

fn options(values: &[i32]) -> Option<i32> {
    let first = values.first()?;
    let doubled = values.get(1).map(|v| v * 2).unwrap_or(0);
    Some(first + doubled)
}

fn invariant(index: usize, len: usize) {
    if index >= len {
        panic!("index {index} out of bounds for length {len}");
    }
    assert!(len > 0, "empty collection");
}