package vc.thinker.exception; import org.eclipse.paho.client.mqttv3.MqttException; import org.springframework.http.HttpStatus; 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.ResponseStatus; import org.springframework.web.bind.annotation.RestController; import org.springframework.web.bind.annotation.RestControllerAdvice; import vc.thinker.response.AbstractResponse; import vc.thinker.response.SimpleResponse; import java.util.List; /** * @author : xieshaojun * @date : 2023/1/3 15:21 */ @RestControllerAdvice(annotations = RestController.class) public class ExceptionAdvice { /** * 缺少参数 * @param e * @return */ @ResponseStatus(HttpStatus.BAD_REQUEST) @ExceptionHandler({MethodArgumentNotValidException.class, BindException.class}) public AbstractResponse handleBodyValidException(MethodArgumentNotValidException e) { AbstractResponse errorResponse = new SimpleResponse(); List<FieldError> fieldErrors = e.getBindingResult().getFieldErrors(); errorResponse.setErrorInfo(HttpStatus.BAD_REQUEST.value(), fieldErrors.get(0).getDefaultMessage()); return errorResponse; } @ResponseStatus(HttpStatus.INTERNAL_SERVER_ERROR) @ExceptionHandler({MqttException.class}) public AbstractResponse mqttException(MqttException e) { AbstractResponse errorResponse = new SimpleResponse(); errorResponse.setErrorInfo(HttpStatus.INTERNAL_SERVER_ERROR.value(), "mqtt连接异常 "+ e.getMessage()); return errorResponse; } /** * 请求过多 * @param e * @return */ @ResponseStatus(HttpStatus.TOO_MANY_REQUESTS) @ExceptionHandler({CurrentLimitException.class}) public AbstractResponse currentLimitException(CurrentLimitException e) { AbstractResponse errorResponse = new SimpleResponse(); errorResponse.setErrorInfo(HttpStatus.TOO_MANY_REQUESTS.value(), e.getMessage()); return errorResponse; } }