package com.example.erp.common.exception; import com.example.erp.common.response.Result; import lombok.extern.slf4j.Slf4j; import org.springframework.validation.FieldError; import org.springframework.web.bind.MethodArgumentNotValidException; import org.springframework.web.bind.annotation.ExceptionHandler; import org.springframework.web.bind.annotation.RestControllerAdvice; @Slf4j @RestControllerAdvice public class GlobalExceptionHandler { @ExceptionHandler(BizException.class) public Result handleBizException(BizException e) { return Result.fail(e.getCode(), e.getMessage()); } @ExceptionHandler(MethodArgumentNotValidException.class) public Result handleValidation(MethodArgumentNotValidException e) { FieldError fe = e.getBindingResult().getFieldErrors().stream().findFirst().orElse(null); String msg = fe != null ? fe.getDefaultMessage() : "参数校验失败"; return Result.fail(40001, msg); } @ExceptionHandler(Exception.class) public Result handleException(Exception e) { log.error("未处理异常", e); return Result.fail(99000, "系统内部错误"); } }