开发者

Switching between exceptions and logging in Java?

I'm on a project wh开发者_StackOverflow社区ere we would like to throw an exception during test, but in production just log the exception instead of throwing it, b/c we don't want to stop execution. Someone suggested Spring might have a way to make this configurable. Any suggestions?


You may use aspect approach in production environment. You need to advise your service class with the appropriate advice which would catch the exception and log it into the syslog. Below code is written according to EJB spec however in Spring it will look like quite similar:

public class CatchExceptionInterceptor{
     private static final Logger log = LoggerFactory.getLogger(CatchExceptionInterceptor.class);
     @AroundInvoke
     public Object invoke(InvocationContext ic){
          try{
                return ic.proceed();
          }catch (Exception e){
                log.error("Error while invoking business method "+e.getMessage(),e);
                return ???// null or whatevery you like
          }
     }
}


Basically, i don't think you should change essential things like exception handling between production and test. You will always have side-effects, e.g. logging the an exception in production can produce another exception etc. However, i have had problems like this myself, and i always solved them by using a central exception Handler, which i could configure to either log messages or rethrow them, or both (not recommended, but product managers want this, until they see that no one can read the logs anymore ;) ).

try {
   doSomethingDangerous();
} catch(Exception e) {
   exceptionHandler.handle(e);
}

Of course, you can use all your imagination on how to get the exceptionHandler, how many different kinds of them you need, what they do with the exception etc. You could also supply a custom message to handle(), or wathever. The thing is, if you centralize this, you can configure the behaviour in one place.


Without much context it's hard to give an advice, but I think you would want to have something like AspectJ (which really nicely integrates with Spring).

In this case, you would create aspect that will attach to all relevant method calls, catch underlying exception, and decide to rethrow or to log it. It would probably be @Around advice.

I , however, question merrits of such approach as if exception is recoverable, there is no need to do anything different between dev and prod environments. It will only complicate testing.


What you are trying to do is problematic, as explained by the other answers (mainly because your exception handlers are part of the software, and should be tested like they run in production). That said, what you are looking for looks more like assertions.

Assertions are commonly enabled in testing only, but not for production. There are several options in Java, the built-in assert, or some 3rd-party library.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜