springMVC實現全局異常處理

你還在爲控制器和service層中的try catch代碼段感到煩惱嗎,每寫一個方法,都要進行try catch或者拋異常處理,然而捕獲到異常之後的處理無非就是告訴用戶,後臺程序出錯了,如果請求的是頁面,則返回用戶一個錯誤頁面,告訴用戶後臺程序出錯了,如果是ajax請求呢,則要返回一個錯誤代碼,告訴前端程序,後臺運行出錯了。所以綜上所屬,無論後臺出現什麼樣的異常,我們只需要在後臺記錄下異常日誌。然後提示用戶後臺程序出錯了即可。所以,根據springmvc中提供的HandlerExceptionResolver接口,然後自己實現了一個全局異常處理類,只需要在spring中註冊遊戲i啊即可。

直接上代碼

package com.jd.trial.common.exception;

import java.io.IOException;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.jd.trial.common.json.JsonResult;
import com.jd.trial.common.utils.AjaxUtils;
import org.apache.log4j.Logger;
import org.springframework.web.servlet.HandlerExceptionResolver;
import org.springframework.web.servlet.ModelAndView;


/**
 * 全局異常處理
 *
 * @ClassName    : ExceptionHandler
 * @Author : ***
 * @CreateDate : 2014年4月23日 下午2:33:43
 */
public class ExceptionHandler implements HandlerExceptionResolver {
    private final Logger log = Logger.getLogger(getClass());
    private String ajaxErrorCode = "ERROR";//ajax 請求錯誤提示
    private String errorUrl = "/showError.htm";//普通請求錯誤後轉發的請求


    public String getAjaxErrorCode() {
        return ajaxErrorCode;
    }

    public void setAjaxErrorCode(String ajaxErrorCode) {
        this.ajaxErrorCode = ajaxErrorCode;
    }

    public String getErrorUrl() {
        return errorUrl;
    }

    public void setErrorUrl(String errorUrl) {
        this.errorUrl = errorUrl;
    }

    /**
     * 全局異常處理
     */
    @Override
    public ModelAndView resolveException(HttpServletRequest request,
                                         HttpServletResponse response, Object handler, Exception ex) {
        log.error(ex.toString(), ex);
        if (isAjaxRequest(request)) {
            log.error(" ajax request error ,return " + ajaxErrorCode);
            try {
                AjaxUtils.write(response, ajaxErrorCode);
            } catch (IOException e) {
                log.error(e.toString(), e);
            }
            return null;
        } else {
            log.error("normal request error ,return "
                    + request.getContextPath() + errorUrl);
            try {
                //request.getRequestDispatcher(errorUrl).forward(request, response);
                response.sendRedirect(errorUrl);
            } catch (IOException e) {
                log.error(e.toString(), e);
            }
        }
        return new ModelAndView();
    }

    /**
     * 判斷request是否爲ajax請求
     *
     * @param request
     * @return : boolean
     * @Method_Name : isAjaxRequest
     * @Creation Date : 2014年4月21日 上午10:51:07
     * @version : v1.00
     * @Author : ***
     * @Update Date :
     * @Update Author :
     */
    private boolean isAjaxRequest(HttpServletRequest request) {
        // return request.getRequestURI().startsWith("/api");
        String requestType = request.getHeader("X-Requested-With");
        return requestType != null && requestType.equals("XMLHttpRequest");
    }
}

然後在spring-servlet.xml中註冊即可,如下示例

    <!-- 全局異常處理配置 start -->
    <bean id="exceptionResolver" class="com.jd.trial.common.exception.ExceptionHandler">
        <property name="ajaxErrorCode" value="${ajaxErrorCode}"></property>
        <!-- ajax 請求錯誤後返回的錯誤代碼,必須int類型 -->
        <property name="errorUrl" value="${errorUrl}"></property>
        <!-- 普通請求錯誤後轉發的請求 -->
    </bean>
    <!-- 全局異常配置 end -->



發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章