标签:问题 image 分享图片 体验 you mod back imp 异常处理
问题描述:当最外层Controller向外抛出异常,会导致页面直接显示异常信息,造成不友好的用户体验
处理思路:
一、配置log4j
● 导入log4j和slf4j的依赖:slf4f是所有日志处理的的规范,推荐用slf4j操作(导入org.slf4j)
<!-- 日志处理 --> <dependency> <groupId>org.slf4j</groupId> <artifactId>slf4j-log4j12</artifactId> <version>${slf4j.version}</version> </dependency>
● 将log4j.properties文件放入resources目录
log4j.rootLogger=INFO,A3,STDOUT log4j.appender.STDOUT=org.apache.log4j.ConsoleAppender log4j.appender.STDOUT.layout=org.apache.log4j.PatternLayout log4j.appender.STDOUT.layout.ConversionPattern=[%p] [%l] %10.10c - %m%n log4j.appender.A3=org.apache.log4j.RollingFileAppender log4j.appender.A3.file=logs/server.log log4j.appender.A3.MaxFileSize=1024KB log4j.appender.A3.MaxBackupIndex=10 log4j.appender.A3.layout=org.apache.log4j.PatternLayout log4j.appender.A3.layout.ConversionPattern=\n\n[%-5p] %d{yyyy-MM-dd HH\:mm\:ss,SSS} method\:%l%n%m%n
二、继承HandlerExceptionResolver来处理异常
package cn.e3mall.search.exception; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.web.servlet.HandlerExceptionResolver; import org.springframework.web.servlet.ModelAndView; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; public class GlobalExceptionResolver implements HandlerExceptionResolver { private static final Logger LOGGER = LoggerFactory.getLogger(GlobalExceptionResolver.class); @Override public ModelAndView resolveException(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, Exception e) { //打印控制台 e.printStackTrace(); //写日志 LOGGER.error("系统发生异常",e); //发邮件通知开发人员debug //TODO //显示错误页面 ModelAndView modelAndView = new ModelAndView(); modelAndView.setViewName("error/exception"); return modelAndView; } }
三、在springmvc配置全局异常处理器
<!--配置全局异常处理器--> <bean class="cn.e3mall.search.exception.GlobalExceptionResolver"/>
四、测试异常处理
在Controller加入如下代码
int i = 1/0;
搜索结果展示错误页面exception.jsp
[ERROR] 2019-01-20 17:18:38,634 method:cn.e3mall.search.exception.GlobalExceptionResolver.resolveException(GlobalExceptionResolver.java:21)
系统发生异常
java.lang.ArithmeticException: / by zero
标签:问题 image 分享图片 体验 you mod back imp 异常处理
原文地址:https://www.cnblogs.com/naixin007/p/10295553.html