总结了一下在使用SPRING开发过程中使用的异常处理方式,查找了一些资料,并在此作为记录。
统一异常处理-使用默认Resolver
使用SimpleMappingExceptionResolver进行处理,这样controller层不需要捕获异常,Spring框架会进行处理。SimpleMappingExceptionResolver是spring的默认实现,但是无法处理AJAX的异常解析
exception/ioexception exception/dbexception
统一异常处理- 使用自定义异常处理器
* 新建自定义异常处理器
public class MyExceptionHandler implements HandlerExceptionResolver{ public ModelAndView resolveException(HttpServletRequest request , HttpServletResponse response,Object handler,Exception ex){ Mapmodel = new HashMap (); model.put("ex",ex); if(ex instanceof ExceptionA){ return new ModelAndView("exception/exception_a",model); }else if(ex instanceof ExceptionB){ return new ModelAndView("exception/exception_b",model); }else{ return new ModelAndView("exception/exception_a",model); } }}
* 新建自定义异常页面* bean声明
统一异常处理-使用@ExceptionHandler注解
* 在Controller的基类中声明方法,这种方法无需任何配置(当然要注解扫描)
@ExceptionHandlerpublic String expaaa(HttpServletRequest request, Exception ex) { request.setAttribute("ex", ex); if(ex instanceof ExceptionA){ return "exception/exception_a"; }else if(ex instanceof ExceptionB){ return "exception/exception_b"; }else{ return "exception/exception_a"; }}
* 其他Controller继承上面的基类
统一异常处理-未捕获异常的处理
在web.xml中定义java.lang.Throwable /500.jsp 500 /500.jsp 404 /404.jsp
大一统-包含表单和AJAX异常处理
* 增加自定义异常处理器,同时如果是AJAX请求,会返回对应的错误回应
public class GlobalExceptionResolver extends SimpleMappingExceptionResolver { protected ModelAndView doResolveException(HttpServletRequest request, HttpServletResponse response,Object handler, Exception ex){ String viewName = determineViewName(ex,request); response.setCharacterEncoding("UTF-8"); if(viewName!=null){ if (!(request.getHeader("accept").contains("application/json") || ( request.getHeader("X-Requested-With")!= null && request.getHeader("X-Requested-With").contains("XMLHttpRequest") ) )) { Integer statusCode = determineStatusCode(request,viewName); if(statusCode !=null){ applyStatusCodeIfPossible(request,response,statusCode); } System.out.println("JSP Format Return" + viewName); return getModelAndView(viewName,ex,request); }else{ try{ PrintWriter writer = response.getWriter(); writer.write(ex.getMessage()); writer.flush(); }catch(IOException e){ e.printStackTrace(); } System.out.println("JSP Format Return" + viewName); return null; } }else{ return null; } }}
* 配置exceptionresolver
exception/ioexception exception/dbexception exception/exception_a exception/exception_b
* DONE