Search code examples
javaexceptionkaratefeature-filecatch-exception

Is there a way to catch org.graalvm.polyglot.PolyglotException in karate, while a (Java) feature step is failing?


While I'm running karate feature files with java classes, the feature file step is failing with org.graalvm.polyglot.PolyglotException and do we have a way to handle those exceptions?

Since there are couple of test cases which has java implementation and these are tested by karate features. i.e., let's assume a java class & feature

Class

public class TestUtil{
 public static void execute(){
  // this value might be null for some use cases & unexpected
  Long unexepectedVal = SomeInternalClass.getValue(); 
  SomeInternalImpl.processAndValidate(unexepectedVal.toString());
 }
}

Feature

Background:
  * def TestUtil = Java.type("pkg")
Scenario:
  * eval TestUtil.execute()

While executing the feature file some use cases, I may get NPE/ConnectionTimeOutException/Other Runtime exceptions and but during the failures I've got org.graalvm.polyglot.PolyglotException as a root exception & how can we trace/print the the original exception in HTML report?.

Trying to catch the org.graalvm.polyglot.PolyglotException and trace the original exception.


Solution

  • You can use a JS try-catch block with the eval keyword. Here is an example that also shows how to use karate.fail() if you still want to fail the test.

    * eval
    """
    try {
      var TestUtil = Java.type("pkg.TestUtil");
      TestUtil.execute();
    } catch (e) {
      karate.logger.error('failed:', e);
      // do your custom cleanup or logging
      karate.fail('failed because of: ' + e);
    }
    """
    

    For further reading: https://github.com/karatelabs/karate/issues/2242

    And also: https://stackoverflow.com/a/75903894/143475

    Besides this I have no suggestions, so if you want any improvements in Karate please consider contributing code.