概念解释
@RestControllerAdvice 是Spring框架中的一个注解,用于定义全局异常处理类。它结合了@ControllerAdvice
和@ResponseBody
的功能,专门用于处理RESTful Web服务的异常。通过使用@RestControllerAdvice
,开发者可以集中处理控制器类中抛出的异常,并返回统一的JSON格式错误信息。
常见用法
1. 全局异常处理
使用@RestControllerAdvice
可以定义一个全局异常处理类,捕获并处理所有控制器中抛出的异常。
示例代码:
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;
@RestControllerAdvice
public class GlobalExceptionHandler {
// 处理自定义异常
@ExceptionHandler(CustomException.class)
public ResponseEntity<ErrorResponse> handleCustomException(CustomException ex) {
ErrorResponse errorResponse = new ErrorResponse(ex.getCode(), ex.getMessage());
return new ResponseEntity<>(errorResponse, HttpStatus.BAD_REQUEST);
}
// 处理所有未捕获的异常