import com.ruyicai.lottery.api.resp.RespBody;
import com.ruyicai.lottery.util.ErrorCode;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import javax.validation.ConstraintViolationException;
@ControllerAdvice
public class RycExceptionAdvice {
private static Logger logger = LoggerFactory.getLogger(RycExceptionAdvice.class);
private static final RespBody ERROR = RespBody.fail(ErrorCode.ERROR);
@ExceptionHandler({Exception.class})
public ResponseEntity handleRunTimeException(Exception e) {
logger.error("system exception", e);
return new ResponseEntity<>(RespBody.fail("403", e.getMessage()), HttpStatus.FORBIDDEN);
}
@ExceptionHandler({IllegalArgumentException.class})
public ResponseEntity<Object> handleRunTimeException(IllegalArgumentException e) {
logger.error("IllegalArgumentException {}", e);
return ResponseEntity.ok(RespBody.fail(ErrorCode.PARAMTER_ERROR.value,e.getMessage()));
}
@ExceptionHandler({MethodArgumentNotValidException.class})
public ResponseEntity handleMethodArgumentNotValidException(MethodArgumentNotValidException e) {
//这个就是处理参数异常报错的
logger.error("MethodArgumentNotValidException {} ", e.getBindingResult().getFieldErrors());
return ResponseEntity.ok(RespBody.fail(ErrorCode.PARAMTER_ERROR.value,e.getBindingResult().getFieldError().getDefaultMessage()));
}
@ExceptionHandler({ConstraintViolationException.class})
public ResponseEntity handleConstraintViolationException(ConstraintViolationException e) {
logger.error("ConstraintViolationException {} ", e.getConstraintViolations().stream().findFirst().get().getMessage());
return ResponseEntity.ok(RespBody.fail(ErrorCode.PARAMTER_ERROR.value,e.getConstraintViolations().stream().findFirst().get().getMessage()));
}
}