Skip to content

ERROR_INJECTING_CONSTRUCTOR

Googler edited this page Aug 12, 2020 · 1 revision

ERROR_INJECTING_CONSTRUCTOR

Summary

Guice will throw an ERROR_INJECTING_CONSTRUCTOR error when a constructor that Guice uses to create objects throws an exception. This can happen with both just-in-time constructor injection and explicit constructor bindings.

Example:

final class Foo {
  @Inject
  Foo(@Nullable Bar bar) {
    // A NullPointerException will be thrown if bar is null.
    bar.doSomething();
  }
}

The NullPointerException thrown from Foo constructor will cause Guice to throw a ProvisionException with an ERROR_INJECTING_CONSTRUCTOR error.

Common Causes

Unexpected exception thrown from constructor

To fix the error, examine and address the associated underlying cause of the error (the cause of the ProvisionException) so that Guice can successfully create the required objects using the class's constructor.

Usually, this can be done by either fixing the code that is throwing exceptions from a constructor:

final class Foo {
  @Inject
  Foo(@Nullable Bar bar) {
    if (bar != null) {
      bar.doSomething();
    }
  }
}

Or, defer the possible exception until after the object has been constructed:

final class Foo {
  private final Bar bar;

  @Inject
  Foo(Bar bar) {
    this.bar = bar;
  }

  void callBar() {
    bar.doSomething(); // bar.doSomething might throw exception
  }
}
Clone this wiki locally