<div class="iteye-blog-content-contain" style="font-size: 14px"></div>
前段时间由于项目需要,做了一下统一异常和日志管理,由spring AOP来完成,统一业务处理放在service层处理,非成功状态统一抛异常。废话不多说,上代码:
用于日志打印的注解类
/**
* 自定义注解 拦截service 方法名称描述
* @author lyl
* @date 2015年12月14日
*/
@Target({ElementType.PARAMETER, ElementType.METHOD})
@Retention(RetentionPolicy.RUNTIME)
@Documented
public @interface SystemServiceLog {
String description() default "";
}
AOP切面类
package com.yzkjchip.aop;
import java.io.IOException;
import java.io.PrintWriter;
import java.io.StringWriter;
import java.lang.reflect.Method;
import java.net.ConnectException;
import java.sql.SQLException;
import java.util.concurrent.CancellationException;
import java.text.ParseException;
import org.apache.log4j.Logger;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.After;
import org.aspectj.lang.annotation.AfterReturning;
import org.aspectj.lang.annotation.AfterThrowing;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.annotation.Pointcut;
import org.hibernate.exception.ConstraintViolationException;
import org.springframework.dao.DataAccessException;
import org.springframework.dao.DataIntegrityViolationException;
import org.springframework.stereotype.Component;
import com.mysql.jdbc.exceptions.jdbc4.MySQLIntegrityConstraintViolationException;
import com.taobao.api.ApiException;
import com.yzkjchip.aop.annotation.SystemControllerLog;
import com.yzkjchip.aop.annotation.SystemServiceLog;
import com.yzkjchip.constants.ErrorCode;
import com.yzkjchip.util.ConstantUtil;
/**
* 异常和日志统一处理
* @author lyl
* @date 2015年12月14日
*/
@Aspect
@Component
public class AspceJAdvice {
/**
* Pointcut 定义Pointcut,Pointcut的名称为aspectjMethod(),此方法没有返回值和参数
* 该方法就是一个标识,不进行调用
* @author lyl
*/
@Pointcut("execution (* com.yzkjchip.service.*.*(..))")
private void aspectjMethod() {
};
/**
* Before 在核心业务执行前执行,不能阻止核心业务的调用。
* @author lyl
* @param joinPoint
* @throws ClassNotFoundException
*/
@Before("aspectjMethod()")
public void before(JoinPoint joinPoint) throws ClassNotFoundException {
String des = getServiceMthodDescription(joinPoint);
Logger log = Logger.getLogger(joinPoint.getTarget().getClass());
if(!des.equals("")){
log.info("方法描述:" + des + " 开始");
}
log.info(getMethodNameAndArgs(joinPoint));
// HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
// if(null != request){
// HttpSession session = request.getSession();
// //TODO token获取 request.getAttribute("token");
// Logger logger = Logger.getLogger(joinPoint.getTarget().getClass());
// logger.info(request.getLocalAddr());
// }
}
/**
* After 核心业务逻辑退出后(包括正常执行结束和异常退出),执行此Advice
* @author lyl
* @param joinPoint
* @throws ClassNotFoundException
*/
@After(value = "aspectjMethod()")
public void after(JoinPoint joinPoint) throws ClassNotFoundException {
String des = getServiceMthodDescription(joinPoint);
if(!des.equals("")){
Logger log = Logger.getLogger(joinPoint.getTarget().getClass());
log.info("方法描述:" + des + " 结束");
}
}
/**
* Around 手动控制调用核心业务逻辑,以及调用前和调用后的处理,
*
* 注意:当核心业务抛异常后,立即退出,转向AfterAdvice 执行完AfterAdvice,再转到ThrowingAdvice
* @author lyl
* @param pjp
* @return
* @throws Throwable
*/
@Around(value = "aspectjMethod()")
public Object around(ProceedingJoinPoint pjp) throws Throwable {
// 调用核心逻辑
Object retVal = pjp.proceed();
return retVal;
}
/**
* AfterReturning 核心业务逻辑调用正常退出后,不管是否有返回值,正常退出后,均执行此Advice
* @author lyl
* @param joinPoint
*/
@AfterReturning(value = "aspectjMethod()", returning = "retVal")
public void afterReturning(JoinPoint joinPoint, String retVal) {
// todo something
}
/**
* 核心业务逻辑调用异常退出后,执行此Advice,处理错误信息
*
* 注意:执行顺序在Around Advice之后
* @author lyl
* @param joinPoint
* @param e
* @throws ClassNotFoundException
*/
@AfterThrowing(value = "aspectjMethod()", throwing = "e")
public void afterThrowing(JoinPoint joinPoint, Throwable e) throws ClassNotFoundException {
String des = getServiceMthodDescription(joinPoint);
Logger log = Logger.getLogger(joinPoint.getTarget().getClass());
log.error("-------------------afterThrowing.handler.start-------------------");
if(!des.equals("")){
log.error("方法描述:" + des);
}
log.error(getMethodNameAndArgs(joinPoint));
log.error("ConstantUtil.getTrace(e): " + getTrace(e));
log.error("异常名称:" + e.getClass().toString());
log.error("e.getMessage():" + e.getMessage());
log.error("-------------------afterThrowing.handler.end-------------------");
// TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
// 在这里判断异常,根据不同的异常返回错误。
if (e.getClass().equals(DataAccessException.class)) {
throw new BusinessException(ErrorCode.DataAccessException.des, ErrorCode.DataAccessException.code);
} else if (e.getClass().toString().equals(ConstraintViolationException.class.toString())) {
throw new BusinessException(ErrorCode.ConstraintViolationException.des, ErrorCode.ConstraintViolationException.code);
} else if (e.getClass().toString().equals(DataIntegrityViolationException.class.toString())) {
throw new BusinessException(ErrorCode.DataIntegrityViolationException.des, ErrorCode.DataIntegrityViolationException.code);
} else if (e.getClass().toString().equals(MySQLIntegrityConstraintViolationException.class.toString())) {
throw new BusinessException(ErrorCode.MySQLIntegrityConstraintViolationException.des, ErrorCode.MySQLIntegrityConstraintViolationException.code);
} else if (e.getClass().toString().equals(NullPointerException.class.toString())) {
throw new BusinessException(ErrorCode.NullPointerException.des, ErrorCode.NullPointerException.code);
} else if (e.getClass().equals(IOException.class)) {
throw new BusinessException(ErrorCode.IOException.des, ErrorCode.IOException.code);
} else if (e.getClass().equals(ClassNotFoundException.class)) {
throw new BusinessException(ErrorCode.ClassNotFoundException.des, ErrorCode.ClassNotFoundException.code);
} else if (e.getClass().equals(ArithmeticException.class)) {
throw new BusinessException(ErrorCode.ArithmeticException.des, ErrorCode.ArithmeticException.code);
} else if (e.getClass().equals(ArrayIndexOutOfBoundsException.class)) {
throw new BusinessException(ErrorCode.ArrayIndexOutOfBoundsException.des, ErrorCode.ArrayIndexOutOfBoundsException.code);
} else if (e.getClass().equals(IllegalArgumentException.class)) {
throw new BusinessException(ErrorCode.IllegalArgumentException.des, ErrorCode.IllegalArgumentException.code);
} else if (e.getClass().equals(ClassCastException.class)) {
throw new BusinessException( ErrorCode.ClassCastException.des, ErrorCode.ClassCastException.code);
} else if (e.getClass().equals(SecurityException.class)) {
throw new BusinessException(ErrorCode.SecurityException.des, ErrorCode.SecurityException.code);
} else if (e.getClass().equals(SQLException.class)) {
throw new BusinessException(ErrorCode.SQLException.des, ErrorCode.SQLException.code);
} else if (e.getClass().equals(NoSuchMethodError.class)) {
throw new BusinessException(ErrorCode.NoSuchMethodError.des, ErrorCode.NoSuchMethodError.code);
} else if (e.getClass().equals(InternalError.class)) {
throw new BusinessException( ErrorCode.InternalError.des, ErrorCode.InternalError.code);
} else if(e.getClass().equals(ConnectException.class)){
throw new BusinessException( ErrorCode.ConnectException.des, ErrorCode.ConnectException.code);
} else if(e.getClass().equals(CancellationException.class)){
throw new BusinessException( ErrorCode.CancellationException.des, ErrorCode.CancellationException.code);
} else if (e.getClass().equals(ApiException.class)) {
throw new BusinessException( ErrorCode.ApiException.des, ErrorCode.ApiException.code);
} else if (e.getClass().equals(ParseException.class)) {
throw new BusinessException( ErrorCode.ParseException.des, ErrorCode.ParseException.code);
} else {
throw new BusinessException(ErrorCode.INTERNAL_PROGRAM_ERROR.des + e.getMessage(), ErrorCode.INTERNAL_PROGRAM_ERROR.code);
}
}
/**
* 获取方法名和参数
* @author lyl
* @param joinPoint
* @return
*/
private String getMethodNameAndArgs(JoinPoint joinPoint){
Object[] args = joinPoint.getArgs();
StringBuffer sb = new StringBuffer("请求方法:");
sb.append(joinPoint.getTarget().getClass().getName() + "."
+ joinPoint.getSignature().getName() + "(");
for (int i = 0; i < args.length; i++) {
sb.append("arg[" + i + "]: " + args[i] + ",");
}
if (args.length > 0) {
sb.deleteCharAt(sb.length() - 1);
}
sb.append(")");
return sb.toString();
}
/**
* 获取注解中对方法的描述信息 用于service层注解
* @author lyl
* @param joinPoint
* @return
* @throws ClassNotFoundException
*/
public static String getServiceMthodDescription(JoinPoint joinPoint)
throws ClassNotFoundException {
String targetName = joinPoint.getTarget().getClass().getName();
String methodName = joinPoint.getSignature().getName();
Object[] arguments = joinPoint.getArgs();
Class targetClass = Class.forName(targetName);
Method[] methods = targetClass.getMethods();
String description = "";
for (Method method : methods) {
if (method.getName().equals(methodName) && method.isAnnotationPresent(SystemServiceLog.class)) {
SystemServiceLog serviceLog = method.getAnnotation(SystemServiceLog.class);
description =serviceLog.description();
break;
}
}
return description;
}
/**
* 获取注解中对方法的描述信息 用于Controller层注解
* @author lyl
* @param joinPoint
* @return
* @throws ClassNotFoundException
*/
public static String getControllerMethodDescription(JoinPoint joinPoint)
throws ClassNotFoundException {
String targetName = joinPoint.getTarget().getClass().getName();
String methodName = joinPoint.getSignature().getName();
Object[] arguments = joinPoint.getArgs();
Class targetClass = Class.forName(targetName);
Method[] methods = targetClass.getMethods();
String description = "";
for (Method method : methods) {
if (method.getName().equals(methodName) && method.isAnnotationPresent(SystemControllerLog.class)) {
SystemControllerLog controllerLog = method.getAnnotation(SystemControllerLog.class);
description =controllerLog.description();
break;
}
}
return description;
}
/**
* 将异常信息输出到log文件
* @param t
* @return
*/
public static String getTrace(Throwable t) {
StringWriter stringWriter= new StringWriter();
PrintWriter writer= new PrintWriter(stringWriter);
t.printStackTrace(writer);
StringBuffer buffer= stringWriter.getBuffer();
return buffer.toString();
}
}
自定义异常类:
package com.yzkjchip.aop;
import org.apache.log4j.Logger;
import com.google.gson.Gson;
import com.yzkjchip.constants.SystemConstants;
import com.yzkjchip.vo.JsonTypeCommonVO;
/**
* 自定义业务异常处理类 友好提示
*
* @author lyl
* @date 2015年12月14日
*/
public class BusinessException extends RuntimeException {
private static final long serialVersionUID = 3152616724785436891L;
private static final Logger log = Logger.getLogger(BusinessException.class);
public static JsonTypeCommonVO<String> jsonTypeCommonVO;
private static Gson gson = new Gson();
public static String json;
public BusinessException(String errorMsg, Number errorCode) {
super(createFriendlyErrMsg(errorMsg, errorCode));
}
public BusinessException(Throwable throwable) {
super(throwable);
}
public BusinessException(Throwable throwable, String errorMsg,
Number errorCode) {
super(throwable);
}
private static String createFriendlyErrMsg(String msgBody, Number errorCode) {
// log.info("msgBody" + msgBody);
if (msgBody.contains("success") && msgBody.contains("errorCode") && msgBody.contains("msg")) {
json = msgBody.substring(msgBody.indexOf("{"), msgBody.indexOf("}") + 1);
log.info(json);
return json;
}
StringBuffer friendlyErrMsg = new StringBuffer();
// friendlyErrMsg.append("抱歉,");
friendlyErrMsg.append(msgBody);
// friendlyErrMsg.append(",请稍后再试或与管理员联系。");
jsonTypeCommonVO = new JsonTypeCommonVO<String>(SystemConstants.SUCCESS_FALSE_FLAG, errorCode, friendlyErrMsg.toString(), null, null);
json = gson.toJson(jsonTypeCommonVO);
log.info(json);
return json;
}
}
错误码(异常码):
package com.thread.daemon.test;
/**
* 李云龙
* 错误码 码表
* @author lyl
* @date 2015年11月6日
*/
public enum ErrorCode {
//-----------------------------统一异常捕获(50***)错误码开始-------------------------------------
/**程序内部错误,操作失败*/
INTERNAL_PROGRAM_ERROR(50000,"程序内部错误,操作失败"),
//说明:以下的异常名称定义,为了可读性均是异常原名,不建议作全部大写‘_’分隔 样式 lyl
/**数据库操作失败*/
DataAccessException(50001,"数据库操作失败"),
/**违反数据库约(唯一)束异常*/
ConstraintViolationException(50002,"对象已经存在,请勿重复操作"),
/**hibernate 违反数据库约(唯一)束异常*/
DataIntegrityViolationException(50003,"对象已经存在,请勿重复操作"),
/**mysql 违反数据库约(唯一)束异常*/
MySQLIntegrityConstraintViolationException(50004,"对象已经存在,请勿重复操作"),
/**空指针异常*/
NullPointerException(50005,"调用了未经初始化的对象或者是不存在的对象"),
/**IO异常*/
IOException(50006,"IO异常"),
/**指定的类不存在*/
ClassNotFoundException(50007,"指定的类不存在"),
/**数学运算异常*/
ArithmeticException(50008,"数学运算异常"),
/**数组下标越界*/
ArrayIndexOutOfBoundsException(50009,"数组下标越界"),
/**方法的参数错误或非法*/
IllegalArgumentException(50010,"参数错误或非法"),
/**类型强制转换错误*/
ClassCastException(50011,"类型强制转换错误"),
/**操作数据库异常*/
SQLException(50013,"操作数据库异常"),
/**违背安全原则异常*/
SecurityException(50012,"违背安全原则异常"),
/**方法末找到异常*/
NoSuchMethodError(50014,"方法末找到异常"),
/**Java虚拟机发生了内部错误*/
InternalError(50015,"内部错误"),
ConnectException(50016,"服务器连接异常"),
CancellationException(50017,"任务已被取消的异常"),
/**Java阿里服务器错误*/
ApiException(50018,"阿里服务器错误"),
/**[日期]或[数值]等转换错误*/
ParseException(50019,"日期格式错误"),
//-----------------------------统一异常捕获(50***)错误码结束-------------------------------------
//-----------------------------参数异常(51***)错误码开始-------------------------------------
ParaIsNull(51002,"参数为空"),
paraNotRight(51003,"参数非法"),
//-----------------------------参数异常(51***)错误码结束-------------------------------------
//-----------------------------公共操作成功、失败(60***)错误码开始-------------------------------------
HANDLER_SUCCESS(60000,"操作成功"),
HANDLER_FAILED(60001,"操作失败"),
SAVE_SUCCESS(60002,"新增成功"),
SAVE_FAILED(60003,"新增失败"),
DELETE_SUCCESS(60004,"删除成功"),
DELETE_FAILED(60005,"删除失败"),
UPDATE_SUCCESS(60006,"修改成功"),
UPDATE_FAILED(60007,"修改失败"),
SET_SUCCESS(60008,"设置成功"),
SET_FAILED(60009,"设置失败"),
/**无对应数据*/
NO_DATA(60010,"无对应数据"),
/**同步成功*/
SYNC_SUCCESS(60011,"同步成功"),
/**同步失败*/
SYNC_FAILED(60012,"同步失败"),
/**同步数据为空*/
SYNC_DATA_IS_NULL(60013,"同步数据为空"),
/**同步数据部分成功*/
SYNC_DATA_NOT_ALL_SUCCESS(60014,"同步数据部分成功"),
/** 查询成功 */
FIND_SUCCESS(60015,"查询成功"),
/** 查询失败 */
FIND_FAILED(60016,"查询失败"),
//-----------------------------公共操作成功、失败(60***)错误码结束-------------------------------------
;
public Number code;
public String des;
private ErrorCode(Number code,String des){
this.code = code;
this.des = des;
}
public static ErrorCode get(Number code){
for(ErrorCode errorCode:ErrorCode.values()){
if(errorCode.code.toString().equals(code.toString())){
return errorCode;
}
}
return null;
}
@Override
public String toString(){
return "code:"+code +", des:"+des;
}
public static void main(String[] args) {
ErrorCode errorCode = get(12001);
if(null != errorCode)
System.out.println(errorCode);
System.err.println(errorCode.code+"<==========>"+errorCode.des);
}
}
springMVC配置:核心
<!--通知spring使用cglib而不是jdk的来生成代理方法 AOP可以拦截到Controller-->
<aop:aspectj-autoproxy proxy-target-class="true"/>
<!-- 注解扫描包 --> <context:component-scan base-package="com" /> <!-- 开启注解 --> <mvc:annotation-driven > </mvc:annotation-driven>
以下是完整配置:
<?xml version="1.0" encoding="UTF-8"?> <beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:context="http://www.springframework.org/schema/context" xmlns:mvc="http://www.springframework.org/schema/mvc" xmlns:aop="http://www.springframework.org/schema/aop" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.2.xsd http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-3.0.xsd http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-3.2.xsd"> <!-- 注解扫描包 --> <context:component-scan base-package="com" /> <!-- 开启注解 --> <mvc:annotation-driven > </mvc:annotation-driven> <!-- 静态资源(js/image)的访问 --> <mvc:resources location="/res/" mapping="/res/**"/> <!-- 定义视图解析器 --> <bean id="viewResolver" class="org.springframework.web.servlet.view.InternalResourceViewResolver"> <property name="prefix" value="/"></property> <property name="suffix" value=".jsp"></property> </bean> <!-- 上传文件拦截,设置最大上传文件大小 10M=10*1024*1024(B)=10485760 bytes --> <bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver"> <property name="maxUploadSize"><value>10485760</value></property> <property name="defaultEncoding"><value>UTF-8</value></property> </bean> <!--通知spring使用cglib而不是jdk的来生成代理方法 AOP可以拦截到Controller--> <aop:aspectj-autoproxy proxy-target-class="true"/> </beans>
spring配置:
核心配置<!-- aop -->
<aop:aspectj-autoproxy/>
以下是完整配置:
<?xml version="1.0" encoding="UTF-8"?> <beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:mvc="http://www.springframework.org/schema/mvc" xmlns:context="http://www.springframework.org/schema/context" xmlns:aop="http://www.springframework.org/schema/aop" xmlns:tx="http://www.springframework.org/schema/tx" xmlns:p="http://www.springframework.org/schema/p" xmlns:task="http://www.springframework.org/schema/task" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-3.0.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.0.xsd http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-3.0.xsd http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-3.0.xsd http://www.springframework.org/schema/task http://www.springframework.org/schema/task/spring-task-3.0.xsd" > <bean id="dataSource" class="com.alibaba.druid.pool.DruidDataSource" init-method="init" destroy-method="close"> <!-- 基本属性 url、user、password --> <property name="url" value="jdbc:mysql://localhost:3306/iamchip?useUnicode=true&characterEncoding=utf-8" /> <property name="username" value="root" /> <property name="password" value="123" /> <!-- 配置初始化大小、最小、最大 --> <property name="initialSize" value="1" /> <property name="minIdle" value="1" /> <property name="maxActive" value="20" /> <!-- 配置获取连接等待超时的时间 --> <property name="maxWait" value="60000" /> <!-- 配置间隔多久才进行一次检测,检测需要关闭的空闲连接,单位是毫秒 --> <property name="timeBetweenEvictionRunsMillis" value="60000" /> <!-- 配置一个连接在池中最小生存的时间,单位是毫秒 --> <property name="minEvictableIdleTimeMillis" value="300000" /> <property name="validationQuery" value="SELECT 'x'" /> <property name="testWhileIdle" value="true" /> <property name="testOnBorrow" value="false" /> <property name="testOnReturn" value="false" /> <!-- 打开PSCache,并且指定每个连接上PSCache的大小 --> <property name="poolPreparedStatements" value="true" /> <property name="maxPoolPreparedStatementPerConnectionSize" value="20" /> <!-- 配置监控统计拦截的filters --> <property name="filters" value="stat" /> </bean> <bean id="sessionFactory" class="org.springframework.orm.hibernate4.LocalSessionFactoryBean"> <property name="dataSource"> <ref bean="dataSource" /> </property> <property name="hibernateProperties"> <props> <prop key="hibernate.dialect"> org.hibernate.dialect.MySQLDialect </prop> <prop key="hibernate.show_sql">true</prop> </props> </property> <property name="packagesToScan" > <list> <value>com.aspectj.entity</value> </list> </property> </bean> <bean id="transactionManager" class="org.springframework.orm.hibernate4.HibernateTransactionManager"> <property name="sessionFactory" ref="sessionFactory" /> </bean> <tx:annotation-driven transaction-manager="transactionManager" /> <bean id="jdbcTemplate" class="org.springframework.jdbc.core.JdbcTemplate"> <property name="dataSource" ref="dataSource" /> </bean> <!-- <bean id="MemcachedService" class="com.yzkjchip.service.MemcachedService" scope="singleton"> </bean> --> <!-- 定时任务 --> <task:annotation-driven scheduler="qbScheduler" mode="proxy"/> <task:scheduler id="qbScheduler" pool-size="10"/> <!-- aop --> <aop:aspectj-autoproxy/>