当我们需要查看程序的错误日志时,我们可以用简单的方法把错误信息保存到数据库,这样我们就能准确定位程序的异常,解决问题。下面我们介绍借助AOP保存错误日志。
package com.allqj.gad_financial_expenditure_java.aspect;
import com.allqj.gad_financial_expenditure_java.entity.result.LogModel;
import com.allqj.gad_financial_expenditure_java.enums.StatusCodeExtendEnum;
import com.allqj.gad_financial_expenditure_java.service.eureka.IUpalogsnodeEurekaService;
import com.allqj.gad_financial_expenditure_java.util.ExceptionUtil;
import com.allqj.qjf.common.exception.BusinessException;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.springframework.stereotype.Component;
import javax.annotation.Resource;
/**
* @Author WF
* @DesCription 保存错误日志
* @Date 2019/5/11 9:21
**/
@Aspect
@Component
public class ErrorLogAop {
//注解里的路径是自己的controller层
@Pointcut("execution(public * com.allqj.gad_financial_expenditure_java.controller..*.*(..))")
public void logPointcut() {
}
@Around("logPointcut()")
public Object doAround(ProceedingJoinPoint proceedingJoinPoint) throws Throwable {
try {
//调用接口,return调用接口的返回值
return proceedingJoinPoint.proceed();
} catch (Exception e) {
//BusinessException是自己写的 异常工具类,自定义异常
if (e instanceof BusinessException) {
System.out.println(((BusinessException) e).getExceptionMessage());
throw e;
} else {
//这里捕获系统异常,如空指针等
//接口名+“ ”+错误信息
System.out.println(e.getStackTrace()[3].toString() + " " + e.getMessage());
}
}
return null;
}
}
调用接口报错后,输出为
**********************java.manager.impl.ExpenditurePageManager.getExpenditurePage(ExpenditurePageManager.java:53) Page index must not be less than zero!
将错误日志保存到数据库清自行操作