package com.example.cattletends.exception; import com.example.cattletends.common.Result; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.http.HttpStatus; import org.springframework.validation.FieldError; 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 java.util.HashMap; import java.util.Map; /** * 全局异常处理器 */ @RestControllerAdvice public class GlobalExceptionHandler { private static final Logger logger = LoggerFactory.getLogger(GlobalExceptionHandler.class); /** * 处理参数校验异常 */ @ExceptionHandler(MethodArgumentNotValidException.class) @ResponseStatus(HttpStatus.BAD_REQUEST) public Result> handleValidationExceptions(MethodArgumentNotValidException ex) { Map errors = new HashMap<>(); ex.getBindingResult().getAllErrors().forEach((error) -> { String fieldName = ((FieldError) error).getField(); String errorMessage = error.getDefaultMessage(); errors.put(fieldName, errorMessage); }); logger.warn("参数校验失败: {}", errors); return Result.error(400, "参数校验失败", errors); } /** * 处理业务异常 */ @ExceptionHandler(RuntimeException.class) @ResponseStatus(HttpStatus.BAD_REQUEST) public Result handleRuntimeException(RuntimeException ex) { logger.error("业务异常: {}", ex.getMessage(), ex); return Result.error(400, ex.getMessage()); } /** * 处理非法参数异常 */ @ExceptionHandler(IllegalArgumentException.class) @ResponseStatus(HttpStatus.BAD_REQUEST) public Result handleIllegalArgumentException(IllegalArgumentException ex) { logger.warn("非法参数: {}", ex.getMessage()); return Result.error(400, ex.getMessage()); } /** * 处理所有其他异常 */ @ExceptionHandler(Exception.class) @ResponseStatus(HttpStatus.INTERNAL_SERVER_ERROR) public Result handleException(Exception ex) { logger.error("系统异常: {}", ex.getMessage(), ex); return Result.error(500, "系统内部错误,请联系管理员"); } }