Spring MVC自定义异常思路

其实springmvc自定义异常很简单,大致分为这四步

  1. 创建自定义异常类并 继承 Exception。
  2. 抛出自定义类的异常(系统dao、service、controller都可能出现异常,都通过throw new 自定义异常类(String message))向上抛出,最后由springmvc前端控制器交给异常处理器进行异常处理。
  3. 创建自定义异常处理器并实现HandlerExceptionResolver。
  4. 配置springmvc.xml的异常处理器



细节:

1.创建自定义异常类并 继承 Exception

public class ItemsException extends Exception{

private String message;


public String getMessage() {

            return message;


}


public void setMessage(String message) {

this.message = message;

}


public ItemsException(String message) {

super();

this.message = message;

}

}


2.抛出自定义类的异常

throw new ItemsException("商品信息不能为空");


3.创建自定义异常处理器并实现HandlerExceptionResolver

public class MyHandlerException implements HandlerExceptionResolver{


                        //obj代表的是抛出异常的位置

public ModelAndView resolveException(HttpServletRequest request, HttpServletResponse response, Object objException exception) {

ModelAndView mav = new ModelAndView();

                         //判断异常的类型 

if(exception instanceof ItemsException){

                        //为自定义的ItemsException异常

                        //强转为ItemsException类型,获取msg信息

ItemsException me = (ItemsException)exception;

                        //添加错误信息,指定跳转的页面

mav.addObject("error", me.getMessage());

                        //这里可以设置跳转到不同的view层

mav.setViewName("error");

}else{

mav.addObject("error", "未知异常");

mav.setViewName("error");

}

                        //最后记得return mav  否则还是会报500错误

                        return mav;

}


}


4.配置springmvc.xml的异常处理器

<!-- springmvc的异常处理器 class为自定义异常处理器的全包名 -->

<bean class="cn.itcats.ssm.exception.MyHandlerException" />





猜你喜欢

转载自blog.csdn.net/itcats_cn/article/details/80369966