'In OSGi, how do you gracefully handle initialisation exceptions?

I am using Maven-SCR. By using the @Component and @Service tags, I can have my class instance register the interfaces it provides automatically.

On occasion, however, the activate method (marked as @Activate) or even the constructor, might throw an exception and fail in a way I can't handle.

The issue is: I want to catch that exception so I can properly log it, but at the same time, I want to prevent that the class publishes its services if it failed to activate or initialize.

How do you guys do this?

Thanks!



Solution 1:[1]

The SCR specification requires exceptions from these methods to be logged to the OSGi LogService. Do you have a LogService implementation bundle installed? If so, you can find the exceptions from these methods logged there. If you need to log these exception to some other log, the you might want to check out something like Pax Logging.

Solution 2:[2]

Firstly I would look into the logging config of your OSGi framework. It should be logging these exceptions.

If that doesn't work, you can just put in this type of code in your annotated method

catch (Exception ex) {  // or RuntimeException if possible
    // log it
    // then rethrow
    throw ex;
}

Note this is considered an anti-pattern by some, due to the duplicate stack traces it tends to produce.

This could also be moved into an aspect although that might cause pain in OSGi.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 bitfox
Solution 2 artbristol