package com.learn.exception; import com.learn.dto.ApiResponse; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.http.HttpStatus; import org.springframework.http.ResponseEntity; import org.springframework.security.access.AccessDeniedException; import org.springframework.web.bind.MethodArgumentNotValidException; import org.springframework.web.bind.annotation.ExceptionHandler; import org.springframework.web.bind.annotation.RestControllerAdvice; import java.util.stream.Collectors; @RestControllerAdvice public class GlobalExceptionHandler { private static final Logger log = LoggerFactory.getLogger(GlobalExceptionHandler.class); /** 参数校验失败 */ @ExceptionHandler(MethodArgumentNotValidException.class) public ResponseEntity> handleValidation(MethodArgumentNotValidException ex) { String detail = ex.getBindingResult().getFieldErrors().stream() .map(e -> e.getField() + ": " + e.getDefaultMessage()) .collect(Collectors.joining("; ")); return ResponseEntity.badRequest().body(ApiResponse.badRequest("参数校验失败: " + detail)); } /** 权限不足(第 3 天) */ @ExceptionHandler(AccessDeniedException.class) public ResponseEntity> handleAccessDenied(AccessDeniedException ex) { return ResponseEntity.status(HttpStatus.FORBIDDEN) .body(ApiResponse.error(403, "权限不足: 只有 ADMIN 可以执行此操作")); } /** 兜底 */ @ExceptionHandler(Exception.class) public ResponseEntity> handleAll(Exception ex) { log.error("未处理异常", ex); return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR) .body(ApiResponse.error(500, "服务器错误: " + ex.getMessage())); } }