转载: http://blog.csdn.net/m13321169565/article/details/7641978

废话不多,直接说重点。

一  创建异常拦截类

(这里将  webapi 和 web异常放在一起处理。但是文件夹是两个的。关于 LogHelper.WebLog和LogHelper.ApiLog)

参见文章:http://blog.csdn.net/hanjun0612/article/details/72639867

  1. public class AnnotationHandlerMethodExceptionResolver extends ExceptionHandlerExceptionResolver {
  2. private String defaultErrorView;
  3. public String getDefaultErrorView() {
  4. return defaultErrorView;
  5. }
  6. public void setDefaultErrorView(String defaultErrorView) {
  7. this.defaultErrorView = defaultErrorView;
  8. }
  9. /***
  10. * 异常后跳转到页面
  11. */
  12. protected ModelAndView doResolveHandlerMethodException(HttpServletRequest request, HttpServletResponse response, HandlerMethod handlerMethod, Exception exception) {
  13. try {
  14. if (handlerMethod == null) {
  15. return null;
  16. }
  17. Method method = handlerMethod.getMethod();
  18. if (method == null) {
  19. return null;
  20. }
  21. ModelAndView returnValue = super.doResolveHandlerMethodException(request, response, handlerMethod, exception);
  22. ResponseBody responseBodyAnn = AnnotationUtils.findAnnotation(method, ResponseBody.class);
  23. if (responseBodyAnn != null) {
  24. ResponseStatus responseStatusAnn = AnnotationUtils.findAnnotation(method, ResponseStatus.class);
  25. if (responseStatusAnn != null) {
  26. HttpStatus responseStatus = responseStatusAnn.value();
  27. String reason = responseStatusAnn.reason();
  28. if (!StringUtils.hasText(reason)) {
  29. response.setStatus(responseStatus.value());
  30. } else {
  31. response.sendError(responseStatus.value(), reason);
  32. }
  33. }
  34. return handleResponseBody(returnValue, request, response);
  35. }
  36. if (returnValue.getViewName() == null) {
  37. returnValue.setViewName(defaultErrorView);
  38. }
  39. return returnValue;
  40. } catch (Exception e) {
  41. LogerHelper.WebLog(e.getMessage());
  42. return null;
  43. }
  44. }
  45. /**
  46. * 异常后 返回json
  47. *
  48. * @param returnValue
  49. * @param request
  50. * @param response
  51. * @return
  52. * @throws ServletException
  53. * @throws IOException
  54. */
  55. @SuppressWarnings({"unchecked", "rawtypes"})
  56. private ModelAndView handleResponseBody(ModelAndView returnValue, HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
  57. try {
  58. Map value = returnValue.getModelMap();
  59. HttpInputMessage inputMessage = new ServletServerHttpRequest(request);
  60. List<MediaType> acceptedMediaTypes = inputMessage.getHeaders().getAccept();
  61. if (acceptedMediaTypes.isEmpty()) {
  62. acceptedMediaTypes = Collections.singletonList(MediaType.ALL);
  63. }
  64. MediaType.sortByQualityValue(acceptedMediaTypes);
  65. HttpOutputMessage outputMessage = new ServletServerHttpResponse(response);
  66. Class<?> returnValueType = value.getClass();
  67. List<HttpMessageConverter<?>> messageConverters = super.getMessageConverters();
  68. if (messageConverters != null) {
  69. for (MediaType acceptedMediaType : acceptedMediaTypes) {
  70. for (HttpMessageConverter messageConverter : messageConverters) {
  71. if (messageConverter.canWrite(returnValueType, acceptedMediaType)) {
  72. messageConverter.write(value, acceptedMediaType, outputMessage);
  73. return new ModelAndView();
  74. }
  75. }
  76. }
  77. }
  78. if (logger.isWarnEnabled()) {
  79. logger.warn("Could not find HttpMessageConverter that supports return type [" + returnValueType + "] and " + acceptedMediaTypes);
  80. }
  81. return null;
  82. } catch (Exception e) {
  83. LogerHelper.ApiLog(e.getMessage());
  84. return null;
  85. }
  86. }
  87. }

二 添加xml配置

找到springmvc-servlet.xml

添加:

  1. <bean id="handlerExceptionResolver" class="com.sanju.sanjuSCM.ExceptionResolver.AnnotationHandlerMethodExceptionResolver">
  2. <property name="defaultErrorView" value="error/500.jsp"/> <!--错误页面-->
  3. <property name="messageConverters">
  4. <list>
  5. <bean class="org.springframework.http.converter.ByteArrayHttpMessageConverter" />
  6. <!-- JSON转换器无需设置mediaType,由外部客户端调用时,手动设置相关mediaType -->
  7. <bean class="org.springframework.http.converter.json.MappingJackson2HttpMessageConverter" />
  8. </list>
  9. </property>
  10. </bean>

就完成了!

====================================================================================

下面是我项目中用到的。
配置文件和上面的还是一样

  1. public class AnnotationHandlerMethodExceptionResolver extends ExceptionHandlerExceptionResolver {
  2.     private String defaultErrorView;
  3.     public String getDefaultErrorView() {
  4.         return defaultErrorView;
  5.     }
  6.     public void setDefaultErrorView(String defaultErrorView) {
  7.         this.defaultErrorView = defaultErrorView;
  8.     }
  9.     /***
  10.      * 异常后跳转到页面
  11.      */
  12.     protected ModelAndView doResolveHandlerMethodException(HttpServletRequest request, HttpServletResponse response, HandlerMethod handlerMethod, Exception exception) {
  13.         Method method=null;
  14.         ModelAndView returnValue=null;
  15.         try {
  16.             if (handlerMethod == null) {
  17.                 return null;
  18.             }
  19.             method = handlerMethod.getMethod();
  20.             if (method == null) {
  21.                 return null;
  22.             }
  23.             returnValue = super.doResolveHandlerMethodException(request, response, handlerMethod, exception);
  24. //这里获取 @RestController和普通 @ResponseBody 的两种注解情况
  25.             Annotation restControllerAnn = method.getDeclaringClass().getAnnotation(RestController.class);
  26.             Annotation responseBodyAnn = restControllerAnn==null
  27.                             ?AnnotationUtils.findAnnotation(method, ResponseBody.class)
  28.                             :restControllerAnn;
  29.             if (responseBodyAnn != null) {
  30.                 ResponseStatus responseStatusAnn = AnnotationUtils.findAnnotation(method, ResponseStatus.class);
  31.                 if (responseStatusAnn != null) {
  32.                     HttpStatus responseStatus = responseStatusAnn.value();
  33.                     String reason = responseStatusAnn.reason();
  34.                     if (!StringUtils.hasText(reason)) {
  35.                         response.setStatus(responseStatus.value());
  36.                     } else {
  37.                         response.sendError(responseStatus.value(), reason);
  38.                     }
  39.                 }
  40.                 return handleResponseBody(returnValue, request, response,handlerMethod,exception);
  41.             }
  42.             if (returnValue.getViewName() == null) {
  43.                 returnValue.setViewName(defaultErrorView);
  44.             }
  45.             return returnValue;
  46.         } catch (Exception e) {
  47.             SimpleDateFormat formatter =new SimpleDateFormat ("yyyy-MM-dd HH:mm:ss"); ;
  48.             String exMsg="\r\n\r\n============================================================\r\n";
  49.             exMsg+="Date : "+(formatter.format(new Date()))+"\r\n\n";
  50.             exMsg+="ErrorMsg : "+exception+"\r\n\n";
  51.             exMsg+="ClassName : "+handlerMethod.getBean().getClass()+"\r\n\n";
  52.             exMsg+="MethodName : "+handlerMethod.getMethod().getName()+"\r\n\n";
  53.             exMsg+="Exception : "+handlerMethod +"\r\n\n";
  54.             LogerHelper.WebLog(exMsg);
  55.             return null;
  56.         }
  57.     }
  58.     /**
  59.      * 异常后 返回json
  60.      *
  61.      * @param returnValue
  62.      * @param request
  63.      * @param response
  64.      * @return
  65.      * @throws ServletException
  66.      * @throws IOException
  67.      */
  68.     @SuppressWarnings({"unchecked", "rawtypes"})
  69.     private ModelAndView handleResponseBody(ModelAndView returnValue, HttpServletRequest request, HttpServletResponse response, HandlerMethod handlerMethod, Exception exception) throws Exception {
  70.         ResultModel rm=new ResultModel();
  71.         rm.setMessage(exception.getMessage());
  72.         try {
  73.             String json= JsonConvert.toJSON(rm);
  74.             response.getWriter().write(json);
  75.             response.getWriter().flush();
  76.             response.getWriter().close();
  77.             return null;
  78.         } catch (Exception e) {
  79.             SimpleDateFormat formatter =new SimpleDateFormat ("yyyy-MM-dd HH:mm:ss"); ;
  80.             String exMsg="\r\n\r\n============================================================\r\n";
  81.             exMsg+="Date : "+(formatter.format(new Date()))+"\r\n\n";
  82.             exMsg+="reqString : "+request.getParameter("reqString")+"\r\n";
  83.             exMsg+="sign : "+request.getParameter("sign") +"\r\n";
  84.             exMsg+="ErrorMsg : "+exception+"\r\n\n";
  85.             exMsg+="ClassName : "+handlerMethod.getBean().getClass()+"\r\n\n";
  86.             exMsg+="MethodName : "+handlerMethod.getMethod().getName()+"\r\n\n";
  87.             exMsg+="Exception : "+handlerMethod +"\r\n\n";
  88.             LogerHelper.ApiLog(exMsg);
  89.             rm.setMessage(e.getMessage());
  90.             String json= JsonConvert.toJSON(rm);
  91.             response.getWriter().write(json);
  92.             response.getWriter().flush();
  93.             response.getWriter().close();
  94.         }
  95. return  null;
  96.     }
  97. }  

SSM 全局异常的更多相关文章

  1. SSM之全局异常处理器

    1. 异常处理思路 首先来看一下在springmvc中,异常处理的思路:   如上图所示,系统的dao.service.controller出现异常都通过throws Exception向上抛出,最后 ...

  2. 使用spring利用HandlerExceptionResolver实现全局异常捕获

    最近一直没有时间更新是因为一直在更新自己使用的框架. 之后会慢慢带来对之前使用的spring+mvc+mybatis的优化. 会使用一些新的特性,实现一些新的功能. 我会尽量分离业务,封装好再拿出来. ...

  3. springmvc 全局异常解决方案

    系统中异常包括两类:预期异常和运行时异常RuntimeException,前者通过捕获异常从而获取异常信息,后者主要通过规范代码开发.测试通过手段减少运行时异常的发生. 系统的dao.service. ...

  4. SpringBoot学习笔记(二):SpringBoot访问静态文件、捕获全局异常、集成Thymeleaf、集成JSP

    SpringBoot访问静态文件 什么是静态文件? 不需要通过web容器去得到的文件,直接通过路径就能得到的文件,比如项目的css,js,img等文件. 所有的资源文件都应该在src/main/res ...

  5. 13.SpringMVC之全局异常

    我们知道,系统中异常包括:编译时异常和运行时异常RuntimeException,前者通过捕获异常从而获取异常信息,后者主要通过规范代码开发.测试通过手段减少运行时异常的发生.在开发中,不管是dao层 ...

  6. 在C#代码中应用Log4Net(四)在Winform和Web中捕获全局异常

    毕竟人不是神,谁写的程序都会有bug,有了bug不可怕,可怕的是出错了,你却不知道错误在哪里.所以我们需要将应用程序中抛出的所有异常都记录起来,不然出了错,找问题就能要了你的命.下面我们主要讨论的是如 ...

  7. MVC 好记星不如烂笔头之 ---> 全局异常捕获以及ACTION捕获

    public class BaseController : Controller { /// <summary> /// Called after the action method is ...

  8. spring设置全局异常处理器

    1.spring设置全局异常,它的原理是向上捕获 spring.xml配置 <!--自定义全局异常处理器--> <bean id="globalExceptionResol ...

  9. atitit.js浏览器环境下的全局异常捕获

    atitit.js浏览器环境下的全局异常捕获 window.onerror = function(errorMessage, scriptURI, lineNumber) { var s= JSON. ...

随机推荐

  1. jqgrid 获取远端数据失败时,弹出错误提示

    有时,我们给jqgrid绑定的远端数据获取失败,此时,需要把错误信息反馈给用户展示,如何实现? 可通过jqgrid的 loadError 来处理错误数据的返回.详细如下: $("#jqGri ...

  2. Mac 如何显示隐藏文件夹并设置快捷键

    通过在终端运行命令可以控制隐藏文件是否显示: 输入defaults write com.apple.finder AppleShowAllFiles NO 就不显示, 输入defaults write ...

  3. Python3入门(二)——Python开发工具Pycharm安装与配置

    一.概述 与IDEA同一家——Jetbrains出品的IDE,强大之处不再赘述 二.安装 点击下载一个合适的版本 参考网友的激活方式激活:https://blog.csdn.net/u01404481 ...

  4. Django Rest Framework源码剖析(一)-----认证

    一.简介 Django REST Framework(简称DRF),是一个用于构建Web API的强大且灵活的工具包. 先说说REST:REST是一种Web API设计标准,是目前比较成熟的一套互联网 ...

  5. 20155301 Exp7 网络欺诈防范

    20155301 Exp7 网络欺诈防范 1.基础问题回答 (1)通常在什么场景下容易受到DNS spoof攻击 (2)在日常生活工作中如何防范以上两攻击方法 2.实践过程记录 简单应用SET工具建立 ...

  6. Qt 的线程与事件循环

    Qt 的线程与事件循环

  7. Hadoop框架

    1.Hadoop的整体框架 Hadoop由HDFS.MapReduce.HBase.Hive和ZooKeeper等成员组成,其中最基础最重要元素为底层用于存储集群中所有存储节点文件的文件系统HDFS( ...

  8. Salesforce随笔: 将Visualforce Page渲染为PDF文件(Render a Visualforce Page as a PDF File)

    参照 : Visualforce Developer Guide 第60页 <Render a Visualforce Page as a PDF File> 你可以用PDF渲染服务生成一 ...

  9. Jenkins分布式构建

    Jenkins分布式构建 有时,如果有一个实例,它是一个更大,更重的项目,需要定期编译生成在许多计算机上.并运行所有这些构建了中央台机器上可能不是最好的选择.在这种情况下,人们可以配置其他Jenkin ...

  10. 更新k8s镜像版本的三种方式

    一.知识准备 更新镜像版本是在k8s日常使用中非常常见的一种操作,本文主要介绍更新介绍的三种方法 二.环境准备 组件 版本 OS Ubuntu 18.04.1 LTS docker 18.06.0-c ...