package com.maternalmall.common; import jakarta.validation.ConstraintViolationException; import org.springframework.web.bind.MethodArgumentNotValidException; import org.springframework.web.bind.annotation.ExceptionHandler; import org.springframework.web.bind.annotation.RestControllerAdvice; @RestControllerAdvice public class GlobalExceptionHandler { @ExceptionHandler(BizException.class) public ApiResponse handleBiz(BizException ex) { return ApiResponse.fail(ex.getMessage()); } @ExceptionHandler(MethodArgumentNotValidException.class) public ApiResponse handleValid(MethodArgumentNotValidException ex) { String msg = ex.getBindingResult().getFieldErrors().stream().findFirst() .map(e -> e.getField() + ":" + e.getDefaultMessage()).orElse("参数错误"); return ApiResponse.fail(msg); } @ExceptionHandler(ConstraintViolationException.class) public ApiResponse handleConstraint(ConstraintViolationException ex) { return ApiResponse.fail(ex.getMessage()); } @ExceptionHandler(Exception.class) public ApiResponse handleUnknown(Exception ex) { return ApiResponse.fail(ex.getMessage()); } }