package com.aida.seller.common.exception; import com.aida.seller.common.result.Response; import com.aida.seller.common.result.ResultEnum; import jakarta.servlet.http.HttpServletRequest; import lombok.extern.slf4j.Slf4j; import org.springframework.http.HttpStatus; import org.springframework.http.ResponseEntity; import org.springframework.validation.BindException; 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; import java.util.stream.Collectors; @Slf4j @RestControllerAdvice public class GlobalExceptionHandler { @ExceptionHandler(UnauthorizedException.class) public ResponseEntity handleUnauthorizedException(UnauthorizedException e) { log.error("Unauthorized: {}", e.getMessage()); return new ResponseEntity<>( Response.fail(401, e.getMessage()), HttpStatus.UNAUTHORIZED ); } @ExceptionHandler(BusinessException.class) public Response handleBusinessException(BusinessException e) { log.error("业务异常: code={}, msg={}", e.getCode(), e.getMsg()); return Response.fail(e.getCode(), e.getMsg()); } @ExceptionHandler(MethodArgumentNotValidException.class) public Response handleValidationException(MethodArgumentNotValidException e) { String message = e.getBindingResult().getFieldErrors().stream() .map(FieldError::getDefaultMessage) .collect(Collectors.joining(", ")); log.error("参数校验异常: {}", message); return Response.fail(ResultEnum.PARAMETER_ERROR.getCode(), message); } @ExceptionHandler(BindException.class) public Response handleBindException(BindException e) { String message = e.getBindingResult().getFieldErrors().stream() .map(FieldError::getDefaultMessage) .collect(Collectors.joining(", ")); log.error("参数绑定异常: {}", message); return Response.fail(ResultEnum.PARAMETER_ERROR.getCode(), message); } @ExceptionHandler(Exception.class) public Response handleException(Exception e) { log.error("系统异常: ", e); return Response.error("system error"); } /** * 处理MinIO异常 */ @ExceptionHandler(MinioException.class) public ResponseEntity handleMinioException(MinioException e) { log.error("[MinioException] {}", e.getMessage(), e); return new ResponseEntity<>( Response.error(e.getMessage()), HttpStatus.INTERNAL_SERVER_ERROR ); } }