Error handler with custom exception (static vs shared library) #279
-
I am currently using the ROS ecosystem and they don't recommend using My goal is to have a custom error when an error occurs while encoding/decoding. The code below achieves what I want automatically (just by including the Is it normal that the static library does not trigger the appropriate ryml callback ? If I use ryml as a shared library, I guess other programs could mess with the callback, so in this case maybe integrating it with the project is a good idea... error_handler.h namespace moveit_serialization {
/// custom ryml runtime_error exception
class yaml_error : public std::runtime_error
{
public:
explicit yaml_error(const std::string& what_arg) : runtime_error(what_arg){};
explicit yaml_error(const char* what_arg) : runtime_error(what_arg){};
};
struct ErrorHandler
{
// this will be called on error
void on_error(const char* msg, size_t len, ryml::Location loc)
{
throw yaml_error(ryml::formatrs<std::string>("{}:{}:{} ({}B): ERROR: {}", loc.name, loc.line, loc.col,
loc.offset, ryml::csubstr(msg, len)));
}
// bridge
ryml::Callbacks callbacks()
{
return ryml::Callbacks(this, nullptr, nullptr, ErrorHandler::s_error);
}
static void s_error(const char* msg, size_t len, ryml::Location loc, void* this_)
{
return ((ErrorHandler*)this_)->on_error(msg, len, loc);
}
ErrorHandler() :trigger defaults(ryml::get_callbacks())
{
ryml::set_callbacks(this->callbacks());
}
ryml::Callbacks defaults;
};
extern ErrorHandler errh;
} // namespace moveit_serialization error_handler.cpp #include <moveit_serialization/ryml/error_handler.h>
namespace moveit_serialization {
// Create and initialize the handler which will set the callback to ryml
ErrorHandler errh;
} // namespace moveit_serialization my_ryml.h // serializers/deserializers functions (not shown)
...
#include <ryml_std.hpp>
#include <moveit_serialization/ryml/error_handler.h>
#include <ryml.hpp> main.cpp #include <my_ryml.h>
int main(int argc, char** argv)
std::string contents = get_file_contents("my_filename");
ryml::Tree tree = ryml::parse_in_arena(ryml::to_csubstr(contents));
ryml::NodeRef root = tree.rootref();
try {
moveit_msgs::MotionPlanRequest mpr;
// deserialize object
root >> mpr;
}
catch (moveit_serialization::yaml_error const& e) {
std::cout << e.what() << std::endl;
} |
Beta Was this translation helpful? Give feedback.
Replies: 1 comment 2 replies
-
I guess it has something to do with: |
Beta Was this translation helpful? Give feedback.
I guess it has something to do with:
https://www.cppstories.com/2018/02/static-vars-static-lib/
https://stackoverflow.com/a/7329177