examples for error handling
MindPatch opened this issue · 2 comments
MindPatch commented
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 commented
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.
knassar702 commented
Thank you