我开始使用mruby并发现我的代码中发生错误的困难方法,但没有错误报告。也许我做错了什么。如何在出现错误时出现错误?
摘自C代码:
mrb = mrb_open();
FILE *f = fopen("example.rb", "r");
mrb_load_file(mrb, f);
fclose(f);
// more C code...
Ruby代码在没有报告的情况下失败:
# example.rb
def my_method
call_undefined_method
end
my_method()
Ruby代码从错误中救出以显示存在错误:
# example.rb
def my_method
call_undefined_method
rescue => e
puts "Error: #{e.message}"
end
my_method()
答案 0 :(得分:4)
您可以通过mrb->exc
#include <mruby.h>
#include <mruby/variable.h>
#include <mruby/string.h>
#include <stdio.h>
int
main(int argc, char* argv[]) {
mrb_state* mrb = mrb_open();
FILE *f = fopen("example.rb", "r");
mrb_value obj = mrb_load_file(mrb, f);
fclose(f);
if (mrb->exc) {
// Error
obj = mrb_funcall(mrb, mrb_obj_value(mrb->exc), "inspect", 0);
fwrite(RSTRING_PTR(obj), RSTRING_LEN(obj), 1, stdout);
putc('\n', stdout);
} else {
obj = mrb_funcall(mrb, obj, "inspect", 0);
fwrite(RSTRING_PTR(obj), RSTRING_LEN(obj), 1, stdout);
putc('\n', stdout);
}
mrb_close(mrb);
return 0;
}