全局异常主要处理controller中抛出的异常,需注意controller中不需要捕获异常
一、@ControllerAdvice + @ExceptionHandler 实现全局异常处理
1、@ControllerAdvice 中申明@ExceptionHandler 方法,对所有controller中的@RequestMapping方法有效。
2、@Controller 中申明@ExceptionHandler 方法,仅对当前controller中的@RequestMapping方法有效。
全局异常处理类GlobalErrorHandler .java代码如下(需保证该类所在路径可以被扫描加载到spring容器):
package com.tianwen.dcdp.exception.handler; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.springframework.web.bind.annotation.ControllerAdvice; import org.springframework.web.bind.annotation.ExceptionHandler; import org.springframework.web.servlet.ModelAndView; import org.springframework.web.servlet.view.json.MappingJackson2JsonView; @ControllerAdvice public class GlobalErrorHandler { /** * 检查是否ajax请求 * @param request * @return */ public static boolean isAjax(HttpServletRequest request) { return request.getHeader("X-Requested-With") != null && "XMLHttpRequest".equalsIgnoreCase(request.getHeader("X-Requested-With")); } /** * 全局异常处理 * @param request * @param response * @param ex * @return * @throws Exception */ @ExceptionHandler(Exception.class) public Object errorHandler(HttpServletRequest request, HttpServletResponse response, Exception ex) throws Exception{ if(isAjax(request)) { //如果是ajax请求,返回json数据 ModelAndView mav = new ModelAndView(new MappingJackson2JsonView()); mav.addObject("result", 0); mav.addObject("msg", ex.getMessage()); return mav; } else { //如果不是ajax请求,跳转到错误页面 ModelAndView mv = new ModelAndView(); mv.addObject("exception", ex); mv.addObject("url", request.getRequestURL()); mv.addObject("msg", ex.getMessage()); if(request.getRequestURL().toString().contains("/m/")) { mv.setViewName("m/error"); } else { mv.setViewName("error"); } return mv; } } }
spring 部分配置如下:
<!-- 自动扫描 --> <context:component-scan base-package="com.tianwen.dcdp"> <context:exclude-filter type="annotation" expression="org.springframework.stereotype.Controller"/> <context:exclude-filter type="annotation" expression="org.springframework.web.bind.annotation.ControllerAdvice"/> </context:component-scan>
springmvc部分配置如下:
<context:component-scan base-package="com.tianwen.dcdp.*"> <context:include-filter type="annotation" expression="org.springframework.stereotype.Controller"/> <context:include-filter type="annotation" expression="org.springframework.web.bind.annotation.ControllerAdvice"/> </context:component-scan>
如此便可实现异常的统一处理
未完待续