Skip to content

Raise Ruby exception in JRuby  #6203

@p-mongo

Description

@p-mongo

I would like to raise an exception class defined in Ruby from Java code. How would one do this?

The examples given in https://github.com/jruby/jruby/wiki/JRuby-Reference#Exceptions all show how to work with Java exceptions, but I would like to raise a Ruby exception.

We have this code:

    try {
      string = (RubyString) value;
    } catch (ClassCastException e) {
      throw context.runtime.newArgumentError(e.toString());
    }

I tried:

        RubyClass cls = this.runTime.getClass("Mongo::GssapiNative::Error");
        RubyString msg = RubyString.newString(context.runtime, message);
        throw cls.newInstance(context, msg, Block.NULL_BLOCK);

This failed with:

src/main/org/mongodb/sasl/GSSAPIAuthenticator.java:141: error: incompatible types: IRubyObject cannot be converted to Throwable
        throw cls.newInstance(context, msg, Block.NULL_BLOCK);
                             ^

So I need to convert my Ruby class instance to a Throwable?

Related question: our existing code supports exception causes, how do I attach those to Ruby exception classes? Is this handled for me automatically somehow?

Thanks in advance.

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions