Skip to content

Confusing error message if exception is thrown from configure #1905

@PBoddington

Description

@PBoddington

If an exception is thrown during an execution of configure, you can get some very confusing error messages. For example, consider the following code.

import com.google.inject.AbstractModule;
import com.google.inject.Guice;
import com.google.inject.Provides;
import jakarta.inject.Singleton;
import java.util.concurrent.ThreadLocalRandom;

class MyClass {

  interface MyInterface {

  }

  static class MyImplementation implements MyInterface {

  }

  static class MyModule extends AbstractModule {

    @Override
    protected void configure() {
      if (ThreadLocalRandom.current().nextBoolean()) {
        throw new RuntimeException("Exception thrown!");
      }
      bind(MyInterface.class).toInstance(new MyImplementation());
    }

    @Provides
    @Singleton
    String provideString(MyInterface myInterface) {
      return "Result";
    }
  }

  public static void main(String[] args) {
    Guice.createInjector(new MyModule());
  }
}

If the RuntimeException is not thrown then the injector is created without issue.
On the other hand, if the RuntimeException is thrown you get a long error message including the following:

Exception in thread "main" com.google.inject.CreationException: Unable to create injector, see the following errors:

1) [Guice/MissingImplementation]: No implementation for MyClass$MyInterface was bound.

Requested by:
1  : MyClass$MyModule.provideString(MyClass.java:43)
      \_ for 1st parameter myInterface
     at MyClass$MyModule.provideString(MyClass.java:43)

Learn more:
  https://github.com/google/guice/wiki/MISSING_IMPLEMENTATION

2) An exception was caught and reported. Message: Exception thrown!
  at [unknown source]

Reporting that no implementation of MyClass$MyInterface is bound is not helpful. In fact what happened is that an exception was thrown from configure before the line creating the binding was reached.

In situations like this where the invocation of configure throws an exception, it probably doesn't make sense to ever report in addition that there are missing bindings.

I am using Guice version 7.0.0.

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