In the process of system development, errors are unavoidable. Although the console will also error when the system goes wrong, but because the system console output too much, often can not quickly locate the wrong function points and reasons. This is done by using annotations, combined with spring's AOP, to make an error output interceptor.
First write an annotation class catcher:
@Target ({Elementtype.method}) @Retention (retentionpolicy.runtime) @Documented @inheritedpublic @interface Catcher { String name ();//Module name}
Then define a slice: exceptioninterceptor
@Aspectpublic class exceptioninterceptor { private logger logger = logger.getlogger (Exceptioninterceptor.class); /** * intercept all exceptions with catcher annotations on the service layer * @param point * @param cat * @param ex */ @AfterThrowing (pointcut= "execution (* com.*.service.*.* (..)) && @annotation (CAT) ", throwing=" ex ") public void servicesite (Joinpoint  POINT,CATCHER CAT,THROWABLE EX) { Stacktraceelement st=ex.getstacktrace () [0]; logger.error (" The module that generated the error: "+cat.name ()); logger.error (" The class that generated the error: "+point.gettarget () . GetclasS (). Getsimplename ()); logger.error ("Method of generating an exception:" + Point.getsignature (). GetName ()); logger.error ("Number of rows in error:" + St.getlinenumber ()); logger.error ("Exception type:" +ex.getClass (). GetName ()); logger.error ("error message:" +ex.getmessage ()); }}
Note: Exceptioninterceptor needs to be defined in Spring.xml
<bean id= "Exceptioninterceptor" class= "Com.util.ExceptionInterceptor" > <property name= "sessionfactory" ref = "Sessionfactory"/></bean>
Usage:
Because the service layer method is intercepted in interceptors (which can also intercept other places), @catcher annotations are added to the method that requires interception.
@Catcher (name= "module required to catch the error") public void test () {throw new RuntimeException ("This module throws an exception");}
When you run this method, the system will get an error:
The class that generated the error: Class name
Method of generating Exception: Test error line number: Corresponding number of rows exception type: RuntimeException error message: An error has occurred
Isn't it intuitive?
This article is from "Mr. Has a Fire" blog, please be sure to keep this source http://88qlp88.blog.51cto.com/4346152/1564347
The simple application of Java annotations in SSH development