异常处理
SpringMVC: HandlerExceptionResolver接口
该接口的每个实现类都是异常的一种处理方式:
 
一、ExceptionHandlerExceptionResolver:主要提供@ExceptionHandler注解,并通过该注解处理异常。
//该方法捕获该类中抛出的ArithmeticException异常
@ExceptionHandler({ArithmeticException.class,ArrayIndexOutOfBoundsException.class})
public ModelAndView testArithmeticException(Exception e){
System.out.println(e);
ModelAndView mv=new ModelAndView("error");
mv.addObject("e",e);
return mv;
}
@ExceptionHandler标识的方法的参数必须是异常类型(Throwable或其子类),不能是其他类型的参数。
 
异常处理路径:最短优先。
如果有两个对应的异常处理方法:优先级是最短优先。
 
@ExceptionHandler只能捕获当前类中的异常。
 
*如果想要捕获其他类中的异常:加@ControllerAdvice。
 
二、ResponseStatusExceptionResolver: 自定义异常显示@ResponseStatus
//自定义异常
@ResponseStatus(value = HttpStatus.FORBIDDEN,reason = "数组越界222")
public class MyArrayIndexOutofBoundsException extends Exception{ }
 
@RequestMapping("testMyException")
public String testMyException(@RequestParam("i") Integer i) throws MyArrayIndexOutofBoundsException {
if(i==3){
throw new MyArrayIndexOutofBoundsException();
}
return "success";
}
@ResponseStatus也可以加在方法前面。
@RequestMapping("testMyException2")
public String testMyException2(@RequestParam("i") Integer i){
if(i==3){
return "redirect:ResponseStatus";//不加前缀后缀
}
return "success";
} @ResponseStatus(value = HttpStatus.FORBIDDEN,reason = "测试")
@RequestMapping("ResponseStatus")
public String testResponseStatus(){
return "success";
}
三、异常处理的实现类:DefaultHandlerExceptionResolver,默认异常处理器
SpringMVC在一些异常的基础上(300 500),新增了一些异常处理。
 
四、SimpleMappingExceptionResolver:通过配置实现异常处理
 
 
 
 

最新文章

  1. d3 中exit() remove()正确工作的方式
  2. XUtils3 的 环境搭建
  3. 史上最全的Linux常用命令
  4. MEF 松耦合
  5. Ajax编程相对路径与绝对路径
  6. sql server DateTime相关内置函数总结
  7. jsp:usebean 常用注意事项
  8. Language Modeling with Gated Convolutional Networks
  9. 最短路径问题(dijkstra-模板)
  10. hadoop端口使用配置总结(非常好的总结)
  11. GNU C 与 ANSI C的区别
  12. HDU6278 Just h-index
  13. .gitlab-ci.yml简介
  14. 分布式监控系统Zabbix3.4-钉钉告警配置记录
  15. 【软件工程Ⅱ】作业四 |个人项目-小学四则运算 “软件”之初版(C语言)
  16. 一键PHP/JAVA安装工具
  17. Python splinter 环境搭建
  18. RealtimeRendering III
  19. [python] 修改Tkinter 的默认图标
  20. BZOJ2169 连边(动态规划)

热门文章

  1. 我把JVM的类加载器整理了一下
  2. DJANGO-天天生鲜项目从0到1-013-订单-支付宝支付
  3. Mysql concat() group_concat()用法
  4. Python网络数据采集PDF高清完整版免费下载|百度云盘
  5. springboot项目部署到tomcat步骤以及常见问题
  6. List接口(动态数组)
  7. Java容器学习之ArrayList
  8. Kaggle 入门题-泰坦尼克号灾难存活预测
  9. Python os.getcwdu() 方法
  10. PHP atan2() 函数