一、背景
- 項目全部接口都是Post + Json接口
- 在Controller層配置參數類型自動轉換
- 使用swagger註解
二、實現方式
@Slf4j
@RestControllerAdvice
public class ControllerExceptionHandler {
private static final String JSON_DESERIALIZER_ERR_TEMP = "參數[%s=%s]格式轉換異常";
@ExceptionHandler(value = HttpMessageNotReadableException.class)
@ResponseStatus(HttpStatus.OK)
public HttpEntity<String> handle(HttpServletRequest request, HttpMessageNotReadableException ex) {
log.error(ex.getMessage(), ex);
Throwable cause = ex.getCause();
if (cause instanceof InvalidFormatException) {
InvalidFormatException formatException = (InvalidFormatException) cause;
List<JsonMappingException.Reference> path = formatException.getPath();
Object value = formatException.getValue();
Optional<JsonMappingException.Reference> optionalReference = path.stream().filter(o -> AnnotationUtils.isCandidateClass(o.getFrom().getClass(), ApiModel.class)).findFirst();
if (optionalReference.isPresent()) {
JsonMappingException.Reference reference = optionalReference.get();
Object object = reference.getFrom();
String fieldName = reference.getFieldName();
Field field = ReflectionUtils.findField(object.getClass(), fieldName);
String fieldDesc = fieldName;
ApiModelProperty annotation = field.getAnnotation(ApiModelProperty.class);
if (Objects.nonNull(annotation)) {
fieldDesc = annotation.value();
}
return new ResponseEntity<>( String.format(JSON_DESERIALIZER_ERR_TEMP, fieldDesc, value), HttpStatus.OK);
}
}
return new ResponseEntity<>("系統繁忙", HttpStatus.OK);
}
}