在Spring Boot中,可以使用@ControllerAdvice和@ExceptionHandler注解来实现全局异常处理。
@ControllerAdvice注解标记。该类可以捕获所有Controller层抛出的异常。@ControllerAdvicepublic class GlobalExceptionHandler {@ExceptionHandler(Exception.class)public ResponseEntity<String> handleException(Exception e) {// 处理异常逻辑return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body("Internal Server Error");}@ExceptionHandler(UserNotFoundException.class)public ResponseEntity<String> handleUserNotFoundException(UserNotFoundException e) {// 处理自定义异常逻辑return ResponseEntity.status(HttpStatus.NOT_FOUND).body(e.getMessage());}}在异常处理方法上使用@ExceptionHandler注解来指定要处理的异常类型。
在处理异常的方法中,可以根据不同的异常类型,进行不同的处理逻辑。
注意:需要添加对应的异常处理类的包扫描,可以使用@ComponentScan注解或在@SpringBootApplication注解上添加scanBasePackages属性来扫描异常处理类所在的包。

