# springmvc_exception
**Repository Path**: yerongli367/springmvc_exception
## Basic Information
- **Project Name**: springmvc_exception
- **Description**: springmvc 异常处理的几种方法
- **Primary Language**: Java
- **License**: Not specified
- **Default Branch**: master
- **Homepage**: None
- **GVP Project**: No
## Statistics
- **Stars**: 0
- **Forks**: 1
- **Created**: 2021-09-18
- **Last Updated**: 2021-09-18
## Categories & Tags
**Categories**: Uncategorized
**Tags**: None
## README
# springMVC 异常处理
#### **==*顶级接口:HandlerExceptionResolver*==**
## 1、@ExceptionHandler
> **该注解由 ==ExceptionHandlerExceptionResolver== 提供**
#### 1.1、捕获 本控制器 中的异常
> 在==Controller(handler) 控制器中== 创建一个异常捕获方法,并使用 @ExceptionHandler(指定要捕获的异常类型) 修饰,
> 该方法 会捕获 本类中出现的 指定异常
```
@ExceptionHandler({ArithmeticException.class})
public String exception(Exception e){
System.out.println("======controller 中的 异常捕捉:"+e);
return "error";
}
```
- 指定 多个异常
```
@ExceptionHandler({ArithmeticException.class,NumberFormatException.class})
```
- 指定 单个异常
```
@ExceptionHandler(ArithmeticException.class)
```
- 注解参数:==需要捕获的异常类.class==。
- 只有方法抛出 指定 异常时 才会调用该方法。
- ==**该注解只能使用在 handler(controller 中)**==
- ==该注解标识的方法的参数 必须在异常类型(Throwable 或 其子类),不能包含其他类型的参数==
- 多个 异常方法 调用 遵循 ==就近原则== 谁离异常近就执行那个异常方法;
- 如:ArithmeticException、Exception 先执行 ArithmeticException 异常捕获方法
## @ExceptionHandler 默认只能 捕获 当前类 中的异常方法.
#### 如果发生异常的方法 和处理 异常的方法 不在同一个类中:通过@ControllerAdvice实现
## 使用 ==@ControllerAdvice== 实现全局异常捕获
- 定义个异常捕捉类 该类使用 @ControllerAdvice 注解修饰
- 类中异常捕捉方法 使用 @ExceptionHandler修饰 使用 ==如上 ↑==
```
@ControllerAdvice
public class GetException {
@ExceptionHandler(RuntimeException.class)
public ModelAndView runtimeException(RuntimeException runtime){
System.out.println("runtimeException 方法异常:"+runtime);
ModelAndView modelAndView = new ModelAndView("error");
modelAndView.addObject("msg",runtime);
return modelAndView;
}
}
```
- 在 springmvc 配置文件中 加入以下配置
```