3

I'm getting started with mruby and found out the hard way that an error was occurring in my code, but there was no error reporting. Maybe I am doing something wrong. How can I get errors to appear when they occur?

Excerpt from C code:

mrb = mrb_open();
FILE *f = fopen("example.rb", "r");
mrb_load_file(mrb, f);
fclose(f);
// more C code...

Ruby code which fails without reporting:

# example.rb
def my_method
  call_undefined_method
end
my_method()

Ruby code which rescues from the error to display that there was an error:

# example.rb
def my_method
  call_undefined_method
rescue => e
  puts "Error: #{e.message}"
end
my_method()
Jay Godse
  • 15,163
  • 16
  • 84
  • 131
Andrew
  • 227,796
  • 193
  • 515
  • 708

1 Answers1

5

You can get exception via 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;
}
mattn
  • 7,571
  • 30
  • 54
  • Any way to get the backtrace? (One has to call the Ruby `backtrace` method or is there a C API function for this?) – thomthom Oct 08 '15 at 22:15
  • 1
    Just realized there is `mrb_print_error(mrb);` - which seems to be a simpler way to print the error. Also found `mrb_print_backtrace(mrb);` but it yields nothing? And `mrb_get_backtrace` yields an empty array. Is this something that isn't implemented? – thomthom Oct 08 '15 at 22:22