ThePhD / sol2

Sol3 (sol2 v3.0) - a C++ <-> Lua API wrapper with advanced features and top notch performance - is here, and it's great! Documentation:
http://sol2.rtfd.io/
MIT License
4.06k stars 493 forks source link

[Feat. Request] Preserve exceptions thrown from C++ #1475

Open saltyJeff opened 1 year ago

saltyJeff commented 1 year ago

Take this code:

#define SOL_ALL_SAFETIES_ON 1
#define SOL_EXCEPTIONS_SAFE_PROPAGATION 1
#include <sol/sol.hpp>
#include <iostream>
#include <stdexcept>

int make_logic_err()
{
    throw std::logic_error("highly illogical jim");
}

int main() {
    sol::state lua;
    lua.open_libraries(sol::lib::base);

    lua["make_logic_err"] = make_logic_err;
    try
    {
        lua.script("error('abc')");
    }
    catch(const std::logic_error& e)
    {
        std::cerr << "logic error caught" << std::endl;
    }
    catch(const std::runtime_error& e)
    {
        std::cerr << "runtime error caught" << std::endl;
    }
    return 0;
}

Godbolt sample: https://godbolt.org/z/e9W1oPf9f

Currently, all C++ exceptions get turned into strings and fed into Lua. Panics in Lua are then converted back to std::runtime_error's with what() set to the Lua error message and stacktrace information.

In my application I'm using custom C++ exceptions, so being able to store original exception information would be very useful for me. I was looking at Lua + Sol2 but I've switched to Chaiscript

Request 1: Preserve std::exception_ptr in sol::error

Scope of changes

  1. Support pushing std::exception_ptr to the stack
  2. In the default exception handler, push exception_ptr, then push the string error message
  3. In the default panic handler, grab the string message, then peek the stack. If the stack contains a exception_ptr, then add it to sol::error

Request 2: Remove stacktrace from sol::error::what()

Scope of changes

  1. Add a stacktrace (maybe just a vector of strings) to sol::error
  2. Instead of appending the stacktrace to the error message, set it to the field

I'm currently working on a dirty hack for request 1, I wanted to get a sense of whether you would accept these changes back into tree and what potential pitfalls you may see.