SpringBoot 全局异常统一处理(AOP):@RestControllerAdvice + @ExceptionHandler + @ResponseStatus
import org.springframework.http.HttpStatus;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseStatus;
import org.springframework.web.bind.annotation.RestControllerAdvice;
import org.springframework.web.servlet.NoHandlerFoundException;
@RestControllerAdvice
public class GlobalExceptionHandler {
@ExceptionHandler(NoHandlerFoundException.class)
@ResponseStatus(HttpStatus.NOT_FOUND)
public String handleNoHandlerFoundException() {
return "No handler found for the request.";
}
@ExceptionHandler(MethodArgumentNotValidException.class)
@ResponseStatus(HttpStatus.BAD_REQUEST)
public String handleValidationExceptions(MethodArgumentNotValidException ex) {
return "Validation failed: " + ex.getBindingResult().toString();
}
// 其他自定义异常处理...
}
这个代码示例展示了如何在Spring Boot应用中使用@RestControllerAdvice
和@ExceptionHandler
注解来实现全局异常处理。这里处理了两种常见的异常类型:NoHandlerFoundException
和MethodArgumentNotValidException
,并且通过@ResponseStatus
注解返回了合适的HTTP状态码。开发者可以根据实际需求添加更多的异常处理逻辑。
评论已关闭