package com.xly.erp.common.exception; import com.xly.erp.common.response.Result; import org.slf4j.Logger; import org.slf4j.LoggerFactory; 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; @RestControllerAdvice public class GlobalExceptionHandler { private static final Logger log = LoggerFactory.getLogger(GlobalExceptionHandler.class); @ExceptionHandler(BizException.class) public Result handleBiz(BizException e) { log.warn("BizException code={} msg={}", e.getCode(), e.getMessage()); return Result.fail(e.getCode(), e.getMessage()); } @ExceptionHandler(MethodArgumentNotValidException.class) public Result handleValidation(MethodArgumentNotValidException e) { FieldError fe = e.getBindingResult().getFieldError(); String msg = fe == null ? "参数校验失败" : fe.getField() + ": " + fe.getDefaultMessage(); log.warn("ValidationException {}", msg); return Result.fail(40001, msg); } @ExceptionHandler(Exception.class) public Result handleAny(Exception e) { log.error("Unhandled exception", e); return Result.fail(50000, "系统繁忙"); } }