4

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!

Miquel
  • 15,405
  • 8
  • 54
  • 87

2 Answers2

2

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.

bitfox
  • 2,281
  • 1
  • 18
  • 17
BJ Hargrave
  • 9,324
  • 1
  • 19
  • 27
  • Allright, so, yes, I should throw the exception so that services are not registered and so on, and if I have a problem with how the exception is handled at the OSGi container level, I can work with the logging configuration to fix it. Good. I think this is the sanest approach. Thanks! (PS: I am using Pax-logging) – Miquel Oct 08 '12 at 11:44
  • Hi @BJ Hargrave, the link that you've provided is not working, could you please update so the others can understand the answer completely. – Agent47 Nov 02 '20 at 11:33
1

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.

artbristol
  • 32,010
  • 5
  • 70
  • 103
  • It does log them, it's just I have less control over them. I think my question was a bit confusing to start of with. I tried to explain what I meant in @BJ Hargrave's answer. Thanks! – Miquel Oct 08 '12 at 11:45