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