SpringBoot Jackson格式反序列異常解析友好顯示

一、背景

  1. 項目全部接口都是Post + Json接口
  2. 在Controller層配置參數類型自動轉換
  3. 使用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);
    }
}

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章