swiftlang / swiftlang/swift-java

Better support for `Error` type in JNI mode.

Open
#826 0 comments 0 reactions 0 assignees View on GitHub

Nobody has claimed this yet.

feature:jextract
Dominant language
Swift
Stars
1.2k
Forks
123
Avg merge
1d 7h
Merged PRs (30d)
16

Description

A common Swift pattern for throwing functions:

enum MyError: Error {
  case firstError
  case secondError
}

func throwingFunc() throws {
  throw MyError.firstError
}

Today in the JNI mode, we can extract throwingFunc and MyError correctly.
However, there is currently no good pattern to know what kind of error was thrown. The best we can do is check the exception message thrown from Java.

It would be nice if we could a type-safe "is this MyError.firstError?"

Accessing the underlying error.

The FFM mode currently has its own SwiftJavaErrorException, which just contains the error description.
In JNI, we just throw a generic Exception with the Error string representation.

With #814 and #819 we can now return protocol types and cast them to their concrete types. If we could do something similiar to FFM mode and wrap a SwiftJavaErrorException that looks like:

public final class SwiftJavaErrorException extends Exception implements JNISwiftInstance {
  public Error getUnderlyingError() {
     // Returns the underlying error from the Swift wrapper.
 }
}

then we could do something like:

try {
  MySwiftLibrary.throwingFunc();
} catch (SwiftJavaErrorException ex) {
  Optional<MyError> myError = ex.getUnderlyingError().as(MyError.class)
  if (myError.isPresent()) {
    // now we can access cases of MyError.
  }
}

Alternative

An alternative solution we could look into is somehow getting MyError to conform to Exception?

Contributor guide

Open the contributing guide

First steps

  1. Read the whole issue, then the project's contributing guide.
  2. Comment on the issue to say you are picking it up — it saves two people doing the same work.
  3. Fork the repository and make your change on a branch.
  4. Open a pull request that references the issue number.

Research direction

Start by comparing the FFM mode's SwiftJavaErrorException with JNI's current generic Exception behavior, then review the protocol-type support described in #814 and #819. Determine whether JNI should expose an underlying Error or use the Exception-conformance alternative; done means callers can identify and access concrete Swift error types without parsing messages.

Written by the indexing model from the issue text.

Assessment

Tech stack
java, swift
Domain
api, backend
Issue type
Feature
Difficulty
5/5
Estimated time
Over a week
Activity status
Quiet
Clarity
Mostly clear
Newbie friendliness
45/100

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.