01_全局异常处理

- **@RestControllerAdvice**

定义全局异常处理类作用在所有的Controller类上

- **@ExceptionHandler**

声明处理异常的方法

## 实现步骤

1. 自定义异常

```java
public class AccountNotFoundException extends Exception {

public AccountNotFoundException() {
}

public AccountNotFoundException(String msg) {
super(msg);
}

}
```

2. 抛出异常

```java
if (employee == null) {
//账号不存在
throw new AccountNotFoundException("账号不存在");//自定义异常
}
```

"账号不存在"会赋值给msg,作为异常信息

3. 全局异常处理器

```java
@RestControllerAdvice
@Slf4j
public class GlobalExceptionHandler {

/**
* 捕获业务异常
* @param ex
* @return
*/
@ExceptionHandler
public Result exceptionHandler(BaseException ex){
log.error("异常信息:{}", ex.getMessage());
return Result.error(ex.getMessage());
}

}
```

posted @ 2024-01-22 20:43  平平无奇的five  阅读(57)  评论(0)    收藏  举报