继承了SimpleMappingExceptionResolver
贴上代码
/** * 对controller异常进行全局处理 * 区分了对普通请求和ajax请求的异常处理,普通请求返回到配置的errorCode页面,或者返回到指定的页面 * @author * */public class CustomException extends SimpleMappingExceptionResolver { private final transient Logger logger = LoggerFactory.getLogger(getClass()); @Override protected ModelAndView doResolveException(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) { String viewName = determineViewName(ex, request); if (viewName != null) { // JSP格式返回 //增加普通提交返回到自己页面errorPage String errorPage = String.valueOf(request.getAttribute("errorPage")); //回到自己的页面 if(StringUtils.isNotBlank(errorPage)){ viewName = errorPage; } if (!(request.getHeader("accept").indexOf("application/json") > -1 || (request .getHeader("X-Requested-With") != null && request .getHeader("X-Requested-With").indexOf("XMLHttpRequest") > -1))) { // 如果不是异步请求 // 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 { // JSON格式返回 try { MapjsonMap = new HashMap (); // 返回是错误 jsonMap.put(BaseController.AJAX_RESULT, false); jsonMap.put(BaseController.RESULT_MESSAGE, ex.getMessage()); response.setContentType("text/html;charset=UTF-8"); PrintWriter writer = response.getWriter(); writer.write(JSON.toJSONString(jsonMap)); writer.close(); } catch (Exception e) { logger.error("doResolveException", "系统异常!", e); } return null; } } else { return null; } }}
spring.xml配置
error/ioexp error/sqlexp