spring异常处理

来源:互联网 发布:淘宝淘口令怎么编辑 编辑:程序博客网 时间:2024/05/01 13:48

spring异常处理基本有3种方式:

1、继承SimpleMappingExceptionResolver类;

applicationContext.xml中添加

<bean class="cn.px.hq.web.resolver.GenericExceptionResolver"><property name="order" value="0"></property><property name="exceptionMappings"><props><prop key="java.lang.Throwable">error/500</prop><prop key="org.apache.shiro.authz.AuthorizationException">error/403</prop></props></property></bean>
或者通过注解@Component实现


实现类GenericExceptionResolver:

 protected ModelAndView doResolveException(HttpServletRequest request,      HttpServletResponse response, Object handler, Exception ex) { ModelAndView modelAndView = null; modelAndView = super.doResolveException(request, response, handler, ex);      if (modelAndView != null) {        Map<String, Object> model = modelAndView.getModel();        model.put("errorCode", exception.getErrorCode().getNumber());        model.put("errorInfo", exception.getErrorInfo());        model.put("data", exception.getProperties());        model.put("message", exception.getMessage());        model.put("stackTrace", exception.getStackTraceAsString()); // 设置异常信息      } return modelAndView;  }


2、实现接口HandlerExceptionResolver ;

applicationContext.xml中增加以下内容:

<bean id="exceptionHandler" class="cn.basttg.core.exception.实现类"/>
实现类代码实现:

public ModelAndView resolveException(HttpServletRequest request, HttpServletResponse response, Object handler,              Exception ex) {          Map<String, Object> model = new HashMap<String, Object>();          model.put("ex", ex);                    // 根据不同错误转向不同页面          if(ex instanceof BusinessException) {              return new ModelAndView("error-business", model);          }else if(ex instanceof ParameterException) {              return new ModelAndView("error-parameter", model);          } else {              return new ModelAndView("error", model);          }      }  


3、@ExceptionHandler注解实现;

/** 基于@ExceptionHandler异常处理 */      @ExceptionHandler      public String exp(HttpServletRequest request, Exception ex) {                    request.setAttribute("ex", ex);                    // 根据不同错误转向不同页面          if(ex instanceof BusinessException) {              return "error-business";          }else if(ex instanceof ParameterException) {              return "error-parameter";          } else {              return "error";          }      }  


原创粉丝点击