ONJava.com -- The Independent Source for Enterprise Java
oreilly.comSafari Books Online.Conferences.

advertisement

AddThis Social Bookmark Button

An Exception Handling Framework for J2EE Applications
Pages: 1, 2, 3, 4, 5, 6

The data coming from exceptioninfo.xml for each exception can be encapsulated into a data transfer object (DTO) named ExceptionInfoDTO. Now we also need a placeholder where we could cache these objects, as we wouldn't want to parse the XML file again and again and create objects each time an exception occurs. This work can be delegated to a class named ExceptionInfoCache, which will cache all ExceptionInfoDTO objects after reading their information from exceptioninfo.xml.

What's this fuss all about, huh? The core of all this is the ExceptionHandler implementation, which will use data encapsulated in ExceptionInfoDTO for getting the message code, creating ExceptionDTO objects, and then logging it based on the type of logging specified in ExceptionInfoDTO for a given exception.

Here is the handleException method of an ExceptionHandler implementation.

public ExceptionDTO handleException(String userId,
      BaseAppException exp) {  
    ExceptionDTO exDTO = new ExceptionDTO();
    ExceptionInfoCache ecache = 
        ExceptionInfoCache.getInstance();
    ExceptionInfo exInfo = ecache
      .getExceptionInfo(
        ExceptionHelper.getClassName(exp));
    String loggingType = null;
    if (exInfo != null) {
        loggingType = exInfo.getLoggingType();
        exDTO.setConfirmation(exInfo
            .isConfirmation());
        exDTO.setMessageCode(exInfo
            .getMessageCode());
    }

    FileLogger logger = new FileLoggerFactory()
        .create();
    logger.logException(exp, loggingType);

Depending upon business requirements, there can be multiple implementations of the ExceptionHandler interface. Deciding which implementation to use can be delegated to a Factory, specifically a ExceptionHandlerFactory class.

Conclusion

Without a comprehensive exception-handing strategy, an ad hoc collection of exception-handling blocks can lead to non-standard error handling and non-maintainable code. Using the above approach, exception handling can be streamlined in a J2EE application.

Resources

ShriKant Vashishtha currently works as a solution architect for Tata Consultancy Services Limited (TCS), India.


Return to ONJava.com.