SpringMVC异常处理

springMVC异常处理

springmvc在处理请求过程中出现异常信息交由异常处理器进行处理,自定义异常处理器可以实现一个系统的异常处理逻辑。

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

简单案例:

1.1 自定义异常类

 

  

public class CustomException extends Exception {

 

/** serialVersionUID*/

 

private static final long serialVersionUID = -5212079010855161498L;

 

public CustomException(String message){

 

super(message);

 

this.message = message;

 

}

 

//异常信息

 

private String message;

 

public String getMessage() {

 

return message;

 

}

 

 

 

public void setMessage(String message) {

 

this.message = message;

 

}

 

}

 

1.2 自定义异常处理器

    

public class CustomExceptionResolver implements HandlerExceptionResolver {

 

 

 

@Override

 

public ModelAndView resolveException(HttpServletRequest request,

 

HttpServletResponse response, Object handler, Exception ex) {

 

ex.printStackTrace();

 

CustomException customException = null;

 

//如果抛出的是系统自定义异常则直接转换

 

if(ex instanceof CustomException){

 

customException = (CustomException)ex;

 

}else{

 

//如果抛出的不是系统自定义异常则重新构造一个系统错误异常。

 

customException = new CustomException("系统错误,请与系统管理 员联系!");

 

}

 

ModelAndView modelAndView = new ModelAndView();

 

modelAndView.addObject("message", customException.getMessage());

 

modelAndView.setViewName("error");

 

return modelAndView;

 

}

 

}

 

 

1.3 异常处理器配置(springmvc.xml中添加

 

 

<!-- 异常处理器 -->

 

<bean id="handlerExceptionResolver" class="cn.itcast.ssm.controller.exceptionResolver.CustomExceptionResolver"/>

1.4 正常测试即可

 

 

 

posted @ 2018-08-19 22:02  向上丶  阅读(204)  评论(0编辑  收藏  举报