GuiceUtils { public static void bindExceptionTrap(Binder binder, Class<?> wrapInterface) throws IllegalArgumentException { Set<Method> disallowed = ImmutableSet.copyOf(Iterables.filter( ImmutableList.copyOf(wrapInterface.getMethods()), Predicates.and(Predicates.not(IS_WHITELISTED), Predicates.not(VOID_METHOD)))); Preconditions.checkArgument(disallowed.isEmpty(), "Non-void methods must be explicitly whitelisted with @AllowUnchecked: " + disallowed); Matcher<Method> matcher = Matchers.not(WHITELIST_MATCHER).and(interfaceMatcher(wrapInterface, false)); binder.bindInterceptor(Matchers.subclassesOf(wrapInterface), matcher, new MethodInterceptor() { @Override public Object invoke(MethodInvocation invocation) throws Throwable { try { return invocation.proceed(); } catch (RuntimeException e) { LOG.warn("Trapped uncaught exception: " + e, e); return null; } } }); } private  GuiceUtils(); static Matcher<Method> interfaceMatcher(
      Class<?> matchInterface,
      boolean declaredMethodsOnly); static void bindJNIContextClassLoader(Binder binder, Class<?> wrapInterface); static void bindExceptionTrap(Binder binder, Class<?> wrapInterface);  }
@Test public void testExceptionTrapping() { Injector injector = Guice.createInjector(new AbstractModule() { @Override protected void configure() { GuiceUtils.bindExceptionTrap(binder(), Flaky.class); bind(Flaky.class).to(NotSoFlakyImpl.class); bind(AlsoFlaky.class).to(NotSoFlakyImpl.class); bind(NotSoFlakyImpl.class).in(Singleton.class); } }); AlsoFlaky flaky = injector.getInstance(AlsoFlaky.class); flaky.get(); flaky.append(ImmutableList.of("hi")); try { flaky.put("hello"); fail("Should have thrown"); } catch (RuntimeException e) { } try { flaky.get(2); fail("Should have thrown"); } catch (RuntimeException e) { } try { flaky.skipped(); fail("Should have thrown"); } catch (RuntimeException e) { } }
@Test(expected = CreationException.class) public void testNoTrappingNonVoidMethods() { Guice.createInjector(new AbstractModule() { @Override protected void configure() { GuiceUtils.bindExceptionTrap(binder(), NonVoid.class); fail("Bind should have failed."); } }); }
@Test public void testWhitelistNonVoidMethods() { Guice.createInjector(new AbstractModule() { @Override protected void configure() { GuiceUtils.bindExceptionTrap(binder(), NonVoidWhitelisted.class); } }); }