Skip to content

Support backtrace_locations with Java exceptions #9458

Closed

Description

@kares

JRuby had supported duck-typing of java.lang.Throwable hierarchy, to act like Ruby's Exception, for a long time.

There's java.lang.Throwable#backtrace which maps the Java stack-trace into an Array.

The backtrace_locations method are a later Ruby language feature and so wasn't considered for addiiton.
It would be desired to support backtrace_location with JRuby's Java integration as well, esp. since frameworks such as Rails might do rescue Exception (which catched Java throwables) and assume backtrace_locations exists.

Activity

  1. chadlwilson commented on May 23, 2026

    @chadlwilson
    Contributor

    For reference, collecting together some of my notes.

    Related issues

    I tried to get Claude to dig across other major libraries/frameworks but it seemed to only find Rails as a core user of backtrace_locations, aside from some MRI-only libraries, and things like sorbet. And for Rails only introduced in Rails 7.1 (Oct 2023) so it's not exactly old. Other libraries all seem to mainly still do string-parsing.

    Some CRuby additional context

    Some uses in the ecosystem:

    Existing JRuby Code
    Existing backtrace impl/place backtrace_locations would need to be implementation:

    @JRubyClass(name = "Java::JavaLang::Throwable")
    public static class Throwable {
    @JRubyMethod // stackTrace => backtrace
    public static IRubyObject backtrace(final ThreadContext context, final IRubyObject self) {
    final Ruby runtime = context.runtime;
    java.lang.Throwable throwable = unwrapIfJavaObject(self);
    // TODO instead this should get aligned with NativeException !?!
    StackTraceElement[] stackTrace = throwable.getStackTrace();
    if ( stackTrace == null ) return context.nil; // never actually happens
    final int len = stackTrace.length;
    if ( len == 0 ) return RubyArray.newEmptyArray(runtime);
    IRubyObject[] backtrace = new IRubyObject[len];
    for ( int i=0; i < len; i++ ) {
    backtrace[i] = newString(context, stackTrace[i].toString());
    }
    return RubyArray.newArrayMayCopy(runtime, backtrace);
    }

    Existing Cruby spec, which could have an equivalent for Java throwables:

    describe "Exception#backtrace_locations" do
    before :each do
    @backtrace = ExceptionSpecs::Backtrace.backtrace_locations
    end
    it "returns nil if no backtrace was set" do
    Exception.new.backtrace_locations.should == nil
    end
    it "returns an Array" do
    @backtrace.should.instance_of?(Array)
    end
    it "sets each element to a Thread::Backtrace::Location" do
    @backtrace.each {|l| l.should.instance_of?(Thread::Backtrace::Location)}
    end
    it "produces a backtrace for an exception captured using $!" do
    exception = begin
    raise
    rescue RuntimeError
    $!
    end
    exception.backtrace_locations.first.path.should =~ /backtrace_locations_spec/
    end
    it "returns an Array that can be updated" do
    begin
    raise
    rescue RuntimeError => e
    e.backtrace_locations.unshift "backtrace first"
    e.backtrace_locations[0].should == "backtrace first"
    end
    end
    end

    Existing Backtrace.backtrace_locations java impl:

    private static class Backtrace {
    private BacktraceData backtraceData;
    private IRubyObject backtraceObject;
    private IRubyObject backtraceLocations;
    public void copy(Backtrace clone) {
    this.backtraceData = clone.backtraceData;
    this.backtraceObject = clone.backtraceObject;
    this.backtraceLocations = clone.backtraceLocations;
    }
    /**
    * Generate a new backtrace (or returns nil if no backtrace data exists).
    * @param runtime
    * @return the generated Ruby backtrace
    */
    public IRubyObject generateBacktrace(Ruby runtime) {
    final BacktraceData backtraceData = this.backtraceData;
    if (backtraceData == null || backtraceData == BacktraceData.EMPTY) return runtime.getNil();
    return TraceType.generateMRIBacktrace(runtime, backtraceData.getBacktrace(runtime));
    }
    /**
    * Generate an array of backtrace location objects for this backtrace.
    *
    * @param context the current thread context
    * @return the array of backtrace locations
    */
    public IRubyObject generateBacktraceLocations(ThreadContext context) {
    final BacktraceData backtraceData = this.backtraceData;
    if (backtraceData == null) return context.nil;
    final Ruby runtime = context.runtime;
    return RubyThread.Location.newLocationArray(runtime, backtraceData.getBacktrace(runtime));
    }
    }

    Existing Thread.backtrace_locations java impl:

    @JRubyMethod
    public IRubyObject backtrace_locations(ThreadContext context) {
    return backtrace_locations(context, null, null);
    }
    @JRubyMethod
    public IRubyObject backtrace_locations(ThreadContext context, IRubyObject level) {
    return backtrace_locations(context, level, null);
    }
    @JRubyMethod
    public IRubyObject backtrace_locations(ThreadContext context, IRubyObject level, IRubyObject length) {
    ThreadContext selfContext = getContext();
    Thread nativeThread = getNativeThread();
    // context can be nil if we have not started or GC has claimed our context
    // nativeThread can be null if the thread has terminated and GC has claimed it
    // nativeThread may have finished
    if (selfContext == null || nativeThread == null || !nativeThread.isAlive()) return context.nil;
    return RubyKernel.withLevelAndLength(
    selfContext, level, length, 0,
    (ctx, lev, len) -> WALKER.walk(getNativeThread().getStackTrace(), stream -> ctx.createCallerLocations(lev, len, stream)));
    }

  2. kares commented on May 26, 2026

    @kares
    MemberAuthor

    so, based on #8665 (comment) (due Rails) it would make sense to have this in 10.0+ rather than just 10.1

  3. kares commented on May 26, 2026

    @kares
    MemberAuthor

    JRuby is missing .exception(message = nil) → self or new_exception on these as well, but perhaps that is not important

    pbly worthy of a separate ticket, personally never used it, instantiating another Java exception (just to change the message) might be tricky. would personally avoid that and not implement feature parity with Ruby Exception. 🤷

  4. chadlwilson commented on May 26, 2026

    @chadlwilson
    Contributor

    Technically I guess backtrace_locations is missing on JRuby 9.4 as well since it's been in Ruby since 2.1, but I didn't specifically test it there (with Rails). That's what the user in the linked issue reported against though.

    I have had weird occasional problems with missing exceptions in a real world Rails 7.2 on JRuby 9.4 app though, just never dug into them sufficiently to know the cause. Might be this, might not be. Took me quite a while to get to Rails 7.1 due to jruby-rack session issues though, so I can perhaps see why id not have noticed it as production apps generally won't go through this Rails code.

    Not quite sure why it went unreported so long though since Rails 7.1 is 2.5 years old now, and maybe 15 months old before that linked issue. I'd have thought there's lots of ways one can end up with a Java Throwable coming out of Rails that ends.up handled here during development? Unless there is some other middleware that is usually handling them earlier before this, even in dev.

  5. chadlwilson commented on May 26, 2026

    @chadlwilson
    Contributor

    JRuby is missing .exception(message = nil) → self or new_exception on these as well, but perhaps that is not important

    pbly worthy of a separate ticket, personally never used it, instantiating another Java exception (just to change the message) might be tricky. would personally avoid that and not implement feature parity with Ruby Exception. 🤷

    Yeah that one seems weird - maybe not worth worrying about.

  6. added this to the JRuby 10.0.6.0 milestone on May 27, 2026
  7. kares commented on May 27, 2026

    @kares
    MemberAuthor

    I have had weird occasional problems with missing exceptions in a real world Rails 7.2 on JRuby 9.4 app though, just never dug into them sufficiently to know the cause

    Not sure how serious this would be, given the ~ EOL status on 9.4. I can leave this issue open for consideration but technically it's a "breaking" change e.g. user-code doing exception.respond_to?(:backtrace_location)...

    You're likely quite deep in the tranches (very much appreciated) with the investigations around jruby-rack etc. 😄
    I am using Rails daily (although embedded only these days) and usually smt like a java.lang.Error not being handled seems rare (acceptable). It's going to depend on specifics of where/when such unexpected Java throwables surface.

  8. headius commented on May 27, 2026

    @headius
    Member

    I believe we should just include this in 10.0+ and not 9.4. If a commercial user depends on 9.4 and requires this to be backported, they will need to work through appropriate channels.

  9. chadlwilson commented on May 27, 2026

    @chadlwilson
    Contributor

    If the cherry pick is/was easy, I was hoping I might do the work to cherry pick it into 9.4.15.0, if that “last patch” is still planned. If it’s not an easy backport, then can leave it.

    For selfish reasons, if nothing else, given I lost quite a number of hours the other day debugging warbler because of problems like this, and also to a lesser extent because GoCD still uses 9.4 (as Ive mentioned before, because Java 21+Ruby 3.4 is/was too aggressive as a minimum and thus was a big jump).

    Would that be considered?

  10. headius commented on May 27, 2026

    @headius
    Member

    If you can do the work to cherrypick it and verify it can get into the 9.4.15 release coming up in the next week or two. We should stop merging forward from 9.4 branch at this point since it is EOL and will only get targeted fixes and subsidized releases after 9.4.15.

    No merging forward means this PR should target 10.0, since we are still merging that forward to 10.1.

  11. chadlwilson commented on May 27, 2026

    @chadlwilson
    Contributor

    Yup, that makes sense to me - I wasn't suggesting targeting 9.4 and merging forward, if that’s how it read. 👍

  12. headius commented on Jun 11, 2026

    @headius
    Member

    Fixed by #9461.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Type

    No type

    Projects

    No projects

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions