package com.greenorange.promotion.exception; import com.greenorange.promotion.common.BaseResponse; import com.greenorange.promotion.common.ErrorCode; import com.greenorange.promotion.common.ResultUtils; import io.swagger.v3.oas.annotations.Hidden; import lombok.extern.slf4j.Slf4j; import org.springframework.http.converter.HttpMessageNotReadableException; import org.springframework.web.bind.MethodArgumentNotValidException; import org.springframework.web.bind.annotation.ExceptionHandler; import org.springframework.web.bind.annotation.RestControllerAdvice; /** * 全局异常处理器 */ @Slf4j @Hidden @RestControllerAdvice public class GlobalExceptionHandler { // 处理参数绑定失败的异常 @ExceptionHandler(MethodArgumentNotValidException.class) public BaseResponse handleMethodArgumentNotValidException(MethodArgumentNotValidException e) { log.error("MethodArgumentNotValidException", e); return ResultUtils.error(ErrorCode.PARAMS_ERROR, "参数验证失败"); } // 处理消息体解析失败的异常 @ExceptionHandler(HttpMessageNotReadableException.class) public BaseResponse handleHttpMessageNotReadableException(HttpMessageNotReadableException e) { log.error("HttpMessageNotReadableException", e); return ResultUtils.error(ErrorCode.PARAMS_ERROR, "请求参数不正确"); } @ExceptionHandler(BusinessException.class) public BaseResponse businessExceptionHandler(BusinessException e) { log.error("BusinessException", e); return ResultUtils.error(e.getCode(), e.getMessage()); } @ExceptionHandler(RuntimeException.class) public BaseResponse runtimeExceptionHandler(RuntimeException e) { log.error("RuntimeException", e); return ResultUtils.error(ErrorCode.SYSTEM_ERROR, "系统错误"); } }