怎么处理出现的异常:
- 不处理:会直接向前端返回500
- 在异常处 try..catch,代码臃肿
- 全局异常处理器:
注解:
- 类的注解:@RestControllerAdvice 声明全局异常处理器类
- 方法的注解:@ExceptionHandler(捕获异常类型):指定处理的异常类型
例:GlobalExceptionHandler.java:
package org.example.ssmpratice1.exception;
import org.example.ssmpratice1.pojo.Result;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;
/**
* 全局异常处理器
*/
@RestControllerAdvice
public class GlobalExceptionHandler {
@ExceptionHandler(Exception.class)//捕获所有异常
public Result exception(Exception e){
e.printStackTrace();
return Result.error("操作异常");
}
}