spring mvc对异常的统一处理

1.在spring-mvc.xml中进行配置
   
   
  1. <bean class="com.test.util.page.WebExceptionResolver" />

2.WebExceptionResolver的实现
   
   
  1. package com.test.util.page;
  2. import org.slf4j.Logger;
  3. import org.slf4j.LoggerFactory;
  4. import org.springframework.web.servlet.HandlerExceptionResolver;
  5. import org.springframework.web.servlet.ModelAndView;
  6. import javax.servlet.http.HttpServletRequest;
  7. import javax.servlet.http.HttpServletResponse;
  8. import java.io.IOException;
  9. public class WebExceptionResolver
  10. implements HandlerExceptionResolver
  11. {
  12. public static final Logger logger = LoggerFactory.getLogger(WebExceptionResolver.class);
  13. public ModelAndView resolveException(HttpServletRequest request, HttpServletResponse response, Object handler, Exception e)
  14. {
  15. try {
  16. if (!(request.getHeader("accept").contains("application/json") ||
  17. (request.getHeader("X-Requested-With") != null && request.getHeader("X-Requested-With").contains("XMLHttpRequest")))) {//不是ajax请求
  18. return new ModelAndView("/exception", "exception", e);
  19. } else {
  20. try {
  21. response.setHeader("REQUEST_ERROR_KEY", "true");
  22. response.setContentType("text/html;charset=utf-8");
  23. response.getWriter().write(new ResponseState(e).toString());
  24. response.getWriter().flush();
  25. response.getWriter().close();
  26. } catch (IOException ex) {
  27. ex.printStackTrace();
  28. }
  29. }
  30. return null;
  31. }finally{
  32. logger.error("系统发生异常,访问路径:" + request.getServletPath());
  33. }
  34. }
  35. }

3.ajax返回实体定义
   
   
  1. package com.test.util.page;
  2. import org.apache.ibatis.exceptions.TooManyResultsException;
  3. import java.sql.SQLException;
  4. /**
  5. * 增删改时返回前端的判断实体
  6. * @author Lihhz 2017-03-15
  7. *
  8. */
  9. public class ResponseState {
  10. /**错误信息*/
  11. protected String message;
  12. /**错误编码*/
  13. protected short code;
  14. /**是否成功*/
  15. protected boolean success;
  16. /**返回数据*/
  17. protected Object data;
  18. public ResponseState() {
  19. this.code = 0;
  20. this.success = true;
  21. this.data = null;
  22. }
  23. public ResponseState(String message) {
  24. this.message = message;
  25. }
  26. public ResponseState(short code, String message) {
  27. this.code = code;
  28. this.message = message;
  29. }
  30. public ResponseState(boolean success, String message) {
  31. this.success = success;
  32. this.message = message;
  33. }
  34. public ResponseState(short code, boolean success, String message) {
  35. this.code = code;
  36. this.success = success;
  37. this.message = message;
  38. }
  39. public ResponseState(Exception ex) {
  40. this.code = -1;
  41. this.success = false;
  42. if (ex.getMessage() == null) {
  43. this.message = "参数不正确或不完整";
  44. } else if (ex.getCause() instanceof SQLException)
  45. this.message = "服务器异常:执行数据库语句错误";
  46. else if(ex.getCause() instanceof TooManyResultsException)
  47. this.message = "应该查询出一条结果,但查询出多条结果.";
  48. else
  49. setMessage(ex.getMessage());
  50. }
  51. public String getMessage() {
  52. return this.message;
  53. }
  54. public void setMessage(String message) {
  55. if (message != null)
  56. message = message.replace("\"", "'").replace('\r', '\0');
  57. this.message = message;
  58. }
  59. public short getCode() {
  60. return this.code;
  61. }
  62. public void setCode(short code) {
  63. this.code = code;
  64. }
  65. public boolean getSuccess() {
  66. return this.success;
  67. }
  68. public void setSuccess(boolean success) {
  69. this.success = success;
  70. }
  71. public Object getData() {
  72. return this.data;
  73. }
  74. public void setData(Object data) {
  75. this.data = data;
  76. }
  77. public String toString() {
  78. StringBuffer sbJson = new StringBuffer("{\"code\":");
  79. sbJson.append(this.code).append(",\"message\":\"").append(this.message)
  80. .append("\",").append("\"success\":").append(this.success)
  81. .append("}");
  82. return sbJson.toString();
  83. }
  84. }

4.对于throw Exception的处理:exception.jsp

   
   
  1. <%@ page language="java" contentType="text/html; charset=utf-8" pageEncoding="utf-8"%>
  2. <%
  3. Exception e = (Exception)request.getAttribute("exception");
  4. %>
  5. <div id='exception-div-11111'></div>
  6. <script type="text/javascript">
  7. alert("服务器发生异常:异常信息:<%=e.getMessage()%>");
  8. //如果是modal的话,关闭,解决页面不能点击的问题
  9. if($('#exception-div-11111').parent().hasClass('modal-content')){
  10. $('#exception-div-11111').parent().parent().parent().modal('hide');
  11. $('#exception-div-11111').parent().parent().parent().removeData("bs.modal");
  12. }
  13. </script>

5.对于post ajax的统一处理
   
   
  1. /**
  2. * jquery的ajax post封装
  3. */
  4. $.postAjax = function(url,data,callback){
  5. $.ajax({
  6. async : false,
  7. url:url,
  8. type:"post",
  9. dataType:"json",
  10. data:data,
  11. // timeout:6000,
  12. beforeSend : loading_start(),
  13. success:function(msg){
  14. if(msg.hasOwnProperty("code") && -1 == msg.code){//异常的统一处理
  15. $.alert(msg.message);
  16. return;
  17. }
  18. callback(msg);
  19. },
  20. error:errorObj,
  21. complete : loading_end()
  22. });
  23. };


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值