mlua-rs / rlua

High level Lua bindings to Rust
Other
1.72k stars 115 forks source link

examples for error handling #258

Closed MindPatch closed 2 years ago

MindPatch commented 2 years ago

it would be better if you provide some examples of error handling, because I've some questions about this in my case I'm trying to create a lua function to send a http request to custom url, but it may return an error message but your crate cannot add Err to the lua_context.create_function function

mod utils;
use rlua::Lua;

const LUA_CODE: &str = include_str!("script.lua"); // example

pub(crate) struct LuaLoader {}

impl LuaLoader {
    pub(crate) fn new() -> LuaLoader {
        LuaLoader {  }
    }

    pub(crate) fn load(&self) {
        let lua_code = Lua::new();
        let sender = utils::Sender::init();
        lua_code.context(move |lua_context| {
            let global = lua_context.globals();
            let sender = lua_context.create_function( |_, _url: String| {
                Ok(sender.send(_url).unwrap())
            });
            global.set("send_req",sender.unwrap()).unwrap();
            lua_context.load(LUA_CODE).exec().unwrap();
        });
    }
}

results

```bash
$ cargo r
https://www.knas.me/
thread 'main' panicked at 'called `Result::unwrap()` on an `Err` value: reqwest::Error { kind: Builder, source
: RelativeUrlWithoutBase }', src/core/mod.rs:20:38
note: run with `RUST_BACKTRACE=1` environment variable to display a backtrace
jugglerchris commented 2 years ago

Hi, The way to return errors from Rust functions is to return the Error::ExternalError variant instead of unwrapping. There are some (admittedly buried) examples in the test suite, e.g. https://github.com/amethyst/rlua/blob/master/tests/tests.rs#L231

If reqwest::Error isn't directly convertible to Box<Error + Send + Sync then you may need to convert it yourself.

MindPatch commented 2 years ago

Thank you