简体   繁体   中英

Using UncaughtExceptionHandler in Struts Application

I have a web application based on Struts 2 MVC. I had to configure proper logging in the application which i already did and its working fine.

What i now want is, i need all the runtime exceptions and error due to system failure (such as lost database connection, any third party service is down etc etc), to be logged in my application log file.

I read about Thread.UncaughtExceptionHandler and also gone through this answer but still unable to get a start for this requirement.

Can someone suggest me how to initiate with this? What classes to make? What to configure? etc etc. Also to tell, there is no multithreading involved in my application.

Thank you!

Below is my log4j.properties

log4j.appender.file=org.apache.log4j.RollingFileAppender
log4j.appender.file.File=${catalina.home}/logs/backlogApp.log
log4j.appender.file.MaxFileSize=1000KB
log4j.appender.file.MaxBackupIndex=1
log4j.appender.file.layout=org.apache.log4j.PatternLayout
log4j.appender.file.layout.ConversionPattern=%d{yyyy-MM-dd HH:mm:ss} %-4p %m%n
log4j.appender.DatePattern='.'yyyy-MM-dd

# Root logger option
log4j.rootLogger=WARN, file
log4j.logger.com.nagarro=WARN

# OFF Hibernate and Spring
log4j.logger.org.hibernate=OFF
log4j.logger.org.springframework=OFF

# OFF all JDBC parameters
log4j.logger.org.hibernate.type=OFF

Also, the global exception handler in struts.xml

<global-results>
        <result name="error">/jsp/errorpage.jsp</result>
        <result name="sessionexpired">/jsp/login.jsp</result>
    </global-results>

    <global-exception-mappings>
        <exception-mapping exception="java.lang.Exception"
            result="error" />
        <exception-mapping exception="javax.persistence.PersistenceException"
            result="error" />
    </global-exception-mappings>

This should basically happen automatically; how are you configuring your logging?

The existing "exception" interceptor can do this, although it is intended more as a way to implement a "go to this page if an exception occurs".

You could use the same idea and write a thin interceptor around action invocation that only logs the relevant exception information and continues on to the action's original result name, but that seems a little wonky, since an RTE should almost certainly interrupt normal flow.

IMO if you're wrapping up functionality that might throw an RTE then:

  • That functionality should already live in a service, and...
  • ...that service should catch exceptions and wrap them in an app-specific exception, and...
  • ...then you can use the existing "exception" interceptor.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM