Skip to content

Python-level exception (PyBaseException?) cannot be directly coerced to Java-level Throwable #362

Open

Description

@doublep

Java method that accepts Throwable cannot be called from Python code with a Python-level exception:

try:
    _do_highlight (objects)
except Exception as exception:
    ErrorUtils.filterError (exception)

The code fails like this: TypeError: filterError(): 1st arg can't be coerced to java.lang.Throwable

I could work around this by adding the following wrapper:

public static void filter_error (PyBaseException exception)
{
    ErrorUtils.filterError (PyException.doRaise (exception, null, null));
}

I'm not sure PyException.doRaise (exception, null, null) is 100% correct, but it seems to mostly work as a way to "coerce" a PyBaseException to a Throwable.

Proposal: make Jython coerce Python-level exceptions to Throwable automatically, as it seems to be possible in general case.

Usecase: I have a Java method that accepts a Throwable and either rethrows it (as a runtime exception if needed) on developer machines or logs and otherwise suppresses on production. The idea is to make bugs on developer machines maximally visible (hard to ignore an exception), but if it still makes it to production in non-critical code, log it, but not let it spoil the full server request.

Basically, request processing looks like this (simplified):

doRealStuff ();  // any exception here (a bug) aborts request processing
try {
    doLessImportantStuff ();  // but exceptions here on production don't result in overall request failure
}
catch (Throwable exception) {
    filterError (exception);
}

where filterError() is basically this:

if (STRICT_MODE)  // i.e. development machine
    throw new RuntimeException (exception);
else  // i.e. production
    justLogIt (exception);

Activity

  1. Stewori commented on Oct 29, 2024

    @Stewori
    Member

    Just one quick thought: Regardless how this issue moves on, your workaround should also work directly from Python, which makes it perhaps a bit more straight forward:

    from PyException import doRaise
    
    try:
        _do_highlight (objects)
    except Exception as exception:
        ErrorUtils.filterError(doRaise(exception.getType(), exception, None))
    

    (Disclaimer: I did not actually test this. Theoretically it should work.)

    I'm not sure PyException.doRaise (exception, null, null) is 100% correct

    As suggested in my code snippet, I think it should be PyException.doRaise(exception.getType(), exception, null).

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

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions