在xml配置
为了能够对异常进行统一的处理,包括普通请求发生异常以及ajax请求发生异常时,我们可以覆写SimpleMappingHandlerExceptionResolver中的doResolveException()方法,判断是普通请求还是ajax请求。
1: package com.wbl.modal.exception;
2:
3: import org.springframework.web.servlet.ModelAndView;
4: import org.springframework.web.servlet.handler.SimpleMappingExceptionResolver;
5:
6: import javax.servlet.http.HttpServletRequest;
7: import javax.servlet.http.HttpServletResponse;
8: import java.io.IOException;
9: import java.io.PrintWriter;
10:
11: /**
12: * Created by Simple_love on 2015/9/10.
13: */
14: public class GlobalExceptionResolver extends SimpleMappingExceptionResolver {
15:
16: @Override
17: protected ModelAndView doResolveException(HttpServletRequest request,
18: HttpServletResponse response, Object handler, Exception ex){
19: String viewName = determineViewName(ex,request);
20: response.setCharacterEncoding("UTF-8");
21: if (viewName != null) {// JSP格式返回
22: if (!(request.getHeader("accept").contains("application/json") || (request.getHeader("X-Requested-With")!= null && request
23: .getHeader("X-Requested-With").contains("XMLHttpRequest") ))) {
24: // 如果不是异步请求
25: // Apply HTTP status code for error views, if specified.
26: // Only apply it if we're processing a top-level request.
27: Integer statusCode = determineStatusCode(request, viewName);
28: if (statusCode != null) {
29: applyStatusCodeIfPossible(request, response, statusCode);
30: }
31: System.out.println("JSP格式返回" + viewName);
32: return getModelAndView(viewName, ex, request);
33: } else {// JSON格式返回
34: try {
35: PrintWriter writer = response.getWriter();
36: writer.write(ex.getMessage());
37: writer.flush();
38: } catch (IOException e) {
39: e.printStackTrace();
40: }
41: System.out.println("JSON格式返回" + viewName);
42: return null;
43: }
44: } else {
45: return null;
46: }
47: }
48: }