SpringMVC 全局異常處理

SpringMVC 異常處理有幾種,這裏使用Spring MVC提供的SimpleMappingExceptionResolverjava

1.定義springMVC全局異常處理類ajax

<!-- springmvc提供的簡單異常處理器 -->
	<bean class="common.exception.CustomExceptionResolver">
		<!-- 定義默認的異常處理頁面 -->
		<property name="defaultErrorView" value="error/500"/>

		<!-- 定義異常處理頁面用來獲取異常信息的變量名,也可不定義,默認名爲exception -->
		<property name="exceptionAttribute" value="ex"/>

		<!-- 定義須要特殊處理的異常
		<property name="exceptionMappings">
			<props>
				<prop key="CustomException">/WEB-INF/jsp/custom_error.jsp</prop>
			</props>
		</property> -->
	</bean>

2.CustomExceptionResolver.java 異常處理類spring

/**
 * 全局異常處理
 * @author rico 2016年5月20日
 *
 */
public class CustomExceptionResolver extends SimpleMappingExceptionResolver {

    // 默認系統exception 提示信息
    private static final String DEFAULT_EXCEPTION_MESSAGE = "系統繁忙";

    @Override
    protected ModelAndView doResolveException(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) {

        if(this.isAjaxRequest(request)) {
            try {
                // ajax 請求
                //logger.error(ex.getMessage(), ex);

                response.setContentType("application/json;charset=UTF-8");
                response.setCharacterEncoding("UTF-8");
                // status 505, 避免與其餘錯誤碼衝突
                response.setStatus(505);

                PrintWriter writer = response.getWriter();
                if(ex instanceof BusinessException) {
                    writer.write(ex.getMessage());
                } else {
                    writer.write(DEFAULT_EXCEPTION_MESSAGE);
                }

                writer.flush();

            } catch (IOException e) {
                e.printStackTrace();
            }
        } else {
            if(ex instanceof BusinessException) {

            } else {
                ex = new BusinessException(StringUtils.isBlank(ex.getMessage())?DEFAULT_EXCEPTION_MESSAGE:ex.getMessage(), ex);
            }

            return super.doResolveException(request, response, handler, ex);
			
			/*// Expose ModelAndView for chosen error view.
			String viewName = determineViewName(ex, request);
			if (viewName != null) {
				// Apply HTTP status code for error views, if specified.
				// Only apply it if we're processing a top-level request.
				Integer statusCode = determineStatusCode(request, viewName);
				if (statusCode != null) {
					applyStatusCodeIfPossible(request, response, statusCode);
				}
				
				return getModelAndView(viewName, ex, request);
			} else {
				return null;
			}*/
        }

        return null;
    }

    /**
     * 判斷是否爲ajax請求
     * @param request
     * @return
     */
    private boolean isAjaxRequest(HttpServletRequest request) {
        String requestType = request.getHeader("X-Requested-With");
        if (requestType != null && requestType.equals("XMLHttpRequest")) {
            return true;
        } else {
            return false;
        }
    }
}

3.錯誤返回處理json

A.頁面返回錯誤mvc

<div class="centers">
	<div class="title">錯誤框</div>
	<span class="error"></span>
	<span class="text"><h1>系統發生內部錯誤。請與管理員聯繫!</h1></span>
	<div class="text"><%=ex.getMessage() %></div>
	<input type="hidden" id="responseText" value="<%=ex.getMessage() %>"/>
</div>

B.Ajax返回錯誤,引入js文件,jQuery ajax全局事件處理app

/**
 * ajax 全局事件
 */
$(document).ajaxComplete(function(event, xhr, settings ) {

});

$(document).ajaxError(function(event, xhr, settings) {
    var responseText = xhr.responseText;

    if(responseText==null || responseText=='') {
        responseText = '系統發生錯誤.';
    }
    alert(responseText);

    /*
    if(xhr.status == '505') {
        var responseText = $('#responseText').val();

        if(responseText==null || responseText=='') {
            responseText = '系統發生錯誤.';
        }

        alert(responseText);
    }*/
});
相關文章
相關標籤/搜索