Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

examples for error handling #258

Closed
MindPatch opened this issue Aug 24, 2022 · 2 comments
Closed

examples for error handling #258

MindPatch opened this issue Aug 24, 2022 · 2 comments

Comments

@MindPatch
Copy link

MindPatch commented Aug 24, 2022

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();
        });
    }
}
  • script.lua
local resp = send_req("https://www.knas.me/")
print(resp.url)
if pcall(send_req("hthtpl")) then
    print("IT WORKS")
else
    print("NOPE")
end

results

$ 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
Copy link
Collaborator

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
Copy link
Author

Thank you

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants