ThinkChat2.0新版上线,更智能更精彩,支持会话、画图、阅读、搜索等,送10W Token,即刻开启你的AI之旅 广告
Spring MVC 在处理请求过程中,出现异常信息交给异常处理器进行处理,自定义异常处理器可以实现一个系统的异常处理逻辑。 系统的DAO(Mapper), Service, Controller出现异常都通过throws Exception向上抛出,最后由Spring MVC前端控制器交给异常处理器进行处理。 ![](https://box.kancloud.cn/4509466cc716ba0af3335e5f37e99041_384x322.png) 1. 编写异常处理类(处理普通请求和ajax请求)。 ~~~ import java.io.IOException; import java.io.PrintWriter; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.web.servlet.HandlerExceptionResolver; import org.springframework.web.servlet.ModelAndView; public class GlobalExceptionResolver implements HandlerExceptionResolver{ private static final Logger logger = LoggerFactory.getLogger(GlobalExceptionResolver.class); @Override public ModelAndView resolveException(HttpServletRequest request, HttpServletResponse response, Object arg2, Exception ex) { // logger.info("系统发生异常"); logger.error("系统发生异常",ex); if (!(request.getHeader("accept").indexOf("application/json") > -1 || (request .getHeader("X-Requested-With")!= null && request .getHeader("X-Requested-With").indexOf("XMLHttpRequest") > -1))) { // 如果不是异步请求 ModelAndView mav = new ModelAndView(); mav.setViewName("/globalerror.html"); return mav; } else {// JSON格式返回 try { PrintWriter writer = response.getWriter(); writer.write(ex.getMessage()); writer.flush(); } catch (IOException e) { e.printStackTrace(); } return null; } } } ~~~ 2. 在springmvc.xml中配置异常处理器 ~~~ <!-- 全局异常处理 --> <bean class="com.neusoft.control.GlobalExceptionResolver"></bean> ~~~ 3. 日志说明 使用slf4j实现日志处理,slf4j内部调用log4j。 需要以下几个jar包 ![](https://box.kancloud.cn/c5e89f8788cae7d0eeacc2ba023fb61d_192x102.png) 在maven环境下,配置依赖: ~~~ <dependency> <groupId>org.slf4j</groupId> <artifactId>slf4j-api</artifactId> <version>1.7.25</version> </dependency> <dependency> <groupId>org.slf4j</groupId> <artifactId>slf4j-log4j12</artifactId> <version>1.7.25</version> <!-- <scope>test</scope> --> </dependency> ~~~ 配置log4j.properties(放在classpath根路径下) ~~~ log4j.rootLogger = INFO,stdout,E ### Console output... 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.E = org.apache.log4j.RollingFileAppender log4j.appender.E.File =D:/logs/error.log log4j.appender.E.MaxFileSize =1024KB log4j.appender.E.MaxBackupIndex =10 log4j.appender.E.Threshold = ERROR log4j.appender.E.layout = org.apache.log4j.PatternLayout log4j.appender.E.layout.ConversionPattern =\n\n[%-5p] %d{yyyy-MM-dd HH\:mm\:ss,SSS} ~~~ 4. Ajax说明 Ajax提交如果出现错误,会返回错误信息,要在error方法中捕获。例如: ~~~ $.ajax({ url:"test/addemp", type:"post", data:{ename:ename,job:job,sal:sal,deptno:deptno}, dataType:"json", success:function(data) { //console.log(data); if(data.result) { alert("保存成功"); } else { alert("保存失败"); } }, error:function(err) { alert("操作失败"); console.log(err); } }); ~~~