1. 程式人生 > >springMVC--全局異常處理

springMVC--全局異常處理

font spa 請求 spring lsi request ann RR javax

全局異常主要處理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>

如此便可實現異常的統一處理

未完待續

springMVC--全局異常處理