栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 系统运维 > 运维 > Linux

仿牛客社区项目笔记-统一处理异常和日志

Linux 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

仿牛客社区项目笔记-统一处理异常和日志

仿牛客社区项目笔记-统一处理异常和日志
  • 1. 统一处理异常和日志
    • 1.1 统一处理异常
    • 1.2 统一处理日志

1. 统一处理异常和日志

分为统一处理异常和统一处理日志。

1.1 统一处理异常

异常一般最后都返回 Controller 层中。我们需要统一处理 Controller 层中的异常。

  1. 将 error 文件夹放在 resources 的 templates 路径下,其中包括 404 和 500.html 页面。
  2. 在 ExceptionAdvice 类中使用 @ControllerAdvice 注解对 Controller 中的异常进行统一处理。其中使用 ExceptionHandler 注解定义异常处理函数。
  3. 发生异常使用日志记录。并且判断请求是同步请求还是异步请求,同步请求重定向 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 统一处理日志
  1. 使用AOP思想,将处理日志的代码写在 ServiceLogAspect 中。
  2. ServiceLogAspect 中首先使用 @Pointcut 定义哪些地方可以被织入。
  3. 利用 @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));
    }

}
转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/842255.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号