neon-bindings / rfcs

RFCs for changes to Neon
Apache License 2.0
14 stars 9 forks source link

RFC: try_catch #29

Closed dherman closed 3 years ago

dherman commented 4 years ago

This RFC proposes a new Context method for catching any JavaScript exceptions that may be thrown during the execution of a computation. The result of the API uses Rust's standard Result enum to distinguish between normal return values and exceptional values:

match cx.try_catch(|cx| { cx.throw(42) }) {
    Ok(v) => { /* ... computation produced a normal result ... */ }
    Err(v) => { /* ... computation threw an exception ... */ }
}

Rendered

kjvalencik commented 4 years ago

A user may choose not to operate on the Result of a try_catch. With the current design, a small amount of boilerplate to transform the Result<Handle<'a, T>, JsValue<'a>> into a JsResult<'a, T> for returning from a method:

let value = match result {
    Ok(v) => Ok(v),
    Err(err) => cx.throw(err)?,
};

I propose adding to this RFC an implementation of JsResultExt to remove ease this boilerplate:

impl <'a, V, E> JsResultExt<'a, V> for Result<Handle<'a, V>, Handle<'a, E>>
where
    V: Value,
    E: Value,
{
    fn or_throw<'b, C: Context<'b>>(self, cx: &mut C) -> JsResult<'a, V> {
        match self {
            Ok(v) => Ok(v),
            Err(err) => cx.throw(err),
        }
    }
}

This would simplify to:

let value = result.or_throw(value)?;
kjvalencik commented 4 years ago

Notes from feature flagged implementation: