仿牛客社区项目笔记-统一处理异常和日志
1. 统一处理异常和日志
分为统一处理异常和统一处理日志。
1.1 统一处理异常
异常一般最后都返回 Controller 层中。我们需要统一处理 Controller 层中的异常。
- 将 error 文件夹放在 resources 的 templates 路径下,其中包括 404 和 500.html 页面。
- 在 ExceptionAdvice 类中使用 @ControllerAdvice 注解对 Controller 中的异常进行统一处理。其中使用 ExceptionHandler 注解定义异常处理函数。
- 发生异常使用日志记录。并且判断请求是同步请求还是异步请求,同步请求重定向 error 文件夹。异步请求返回 Json 字符串。
@ControllerAdvice(annotations = Controller.class)
public class ExceptionAdvice {
private static final Logger logger = LoggerFactory.getLogger(ExceptionAdvice.class);
@ExceptionHandler({Exception.class})
public void handleException(Exception e, HttpServletRequest request, HttpServletResponse response) throws IOException {
logger.error("服务器发生异常: " + e.getMessage());
for (StackTraceElement element : e.getStackTrace()) {
logger.error(element.toString());
}
String xRequestedWith = request.getHeader("x-requested-with");
if ("XMLHttpRequest".equals(xRequestedWith)) {
response.setContentType("application/plain;charset=utf-8");
PrintWriter writer = response.getWriter();
writer.write(CommunityUtil.getJSONString(1, "服务器异常!"));
} else {
response.sendRedirect(request.getContextPath() + "/error");
}
}
}
1.2 统一处理日志
- 使用AOP思想,将处理日志的代码写在 ServiceLogAspect 中。
- ServiceLogAspect 中首先使用 @Pointcut 定义哪些地方可以被织入。
- 利用 @Before 在连接点方法执行前执行逻辑,打印:用户[1.2.3.4],在[xxx],访问了[com.nowcoder.community.service.xxx()]。
@Component
@Aspect
public class ServiceLogAspect {
private static final Logger logger = LoggerFactory.getLogger(ServiceLogAspect.class);
// 定义哪些地方可以被织入。
@Pointcut("execution(* com.nowcoder.community.service.*.*(..))")
public void pointcut() {
}
//在连接点方法前执行。
@Before("pointcut()")
public void before(JoinPoint joinPoint) {
// 打印:用户[1.2.3.4],在[xxx],访问了[com.nowcoder.community.service.xxx()].
//使用 RequestContextHolder 获得 request。
ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
HttpServletRequest request = attributes.getRequest();
String ip = request.getRemoteHost();
String now = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date());
//使用joinPoint参数获得类名和方法
String target = joinPoint.getSignature().getDeclaringTypeName() + "." + joinPoint.getSignature().getName();
logger.info(String.format("用户[%s],在[%s],访问了[%s].", ip, now, target));
}
}