如何在json请求中向未知字段抛出错误以弹出restapi

时间:2017-03-30 14:07:11

标签: spring spring-mvc spring-boot jackson spring-rest

我有一个spring rest api,它获取json数据并绑定到pojo GetData。 每当我收到未知字段时,它都不会失败或抛出任何异常。我的要求是它在json数据中接收未知字段时应该抛出错误。

DataFrame

以下是我的Pojo GetData

public ResponseEntity<Error> saveLocation(@Valid @RequestBody GetData getdata,BindingResult bindingResults) {

以下是我的json请求。

public class GetData{

@JsonProperty("deviceID")
@Pattern(regexp="^[\\p{Alnum}][-\\p{Alnum}\\p{L}]+[\\p{Alnum}]$",message = "Not a valid Device Id")
private String deviceID;


@JsonProperty("Coordinates")
@Pattern(regexp="^[\\p{Alnum}\\-][\\.\\,\\-\\_\\p{Alnum}\\p{L}\\s]+|",message = "Coordinates are not valid")
private String coordinates;}

现在,如果我发送带有额外字段的请求,请说国家/地区。它不会抛出任何错误。

{
"deviceID" : "01dbd619-843b-4197-b954",
"Coordinates" : "12.984012,80.246712",
}

请建议如何在json请求中发送未知属性时出现错误

3 个答案:

答案 0 :(得分:1)

您可以尝试以下任一实现,它对我有用。您将不得不从ResponseEntityExceptionHandler或使用ExceptionHandler覆盖另一种方法。

1。通过ResponseEntityExceptionHandler的重写方法

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.http.converter.HttpMessageNotReadableException;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.context.request.WebRequest;
import org.springframework.web.servlet.mvc.method.annotation.ResponseEntityExceptionHandler;


@ControllerAdvice
public class CustomExceptionHandler extends ResponseEntityExceptionHandler {

    private static final Logger log = LoggerFactory.getLogger(CustomExceptionHandler.class);

    //Other Handlers

    // Handle 400 Bad Request Exceptions

    @Override
    protected ResponseEntity<Object> handleHttpMessageNotReadable(HttpMessageNotReadableException ex, HttpHeaders headers, HttpStatus status, WebRequest request) {
        log.info(ex.getLocalizedMessage() + " ",ex);

        final CustomErrorMessage errorMessage = new CustomErrorMessage(ex.getLocalizedMessage(), InfoType.ERROR, HttpStatus.BAD_REQUEST, ex.fillInStackTrace().toString());
        return handleExceptionInternal(ex, errorMessage, headers, errorMessage.getStatus(), request);
    }

    //Other Handlers
}

除了上述实现之外,如果仅当请求有效负载中存在无法识别的属性或空属性并且出现空值(如JSON之下)时,如果您想引发错误,您也可以尝试以下方法

   {
     "":""
   }

2。使用ExceptionHandler

import com.fasterxml.jackson.databind.exc.UnrecognizedPropertyException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.core.Ordered;
import org.springframework.core.annotation.Order;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseStatus;


@Order(Ordered.HIGHEST_PRECEDENCE)
@ControllerAdvice
public class GenericExceptionHandler {

    private static final Logger log = LoggerFactory.getLogger(GenericExceptionHandler.class);

    @ExceptionHandler(value = {UnrecognizedPropertyException.class})
    @ResponseStatus(HttpStatus.BAD_REQUEST)
    protected ResponseEntity<Object> handleUnrecognizedPropertyException(UnrecognizedPropertyException ex) {
        log.info(ex.getLocalizedMessage() + " ",ex);

        final String error = "JSON parse error: Unrecognized field " + "[ " + ex.getPropertyName() + " ]";

        final CustomErrorMessage errorMessage = new CustomErrorMessage(error, InfoType.ERROR, HttpStatus.BAD_REQUEST);
        return ResponseEntity.status(HttpStatus.BAD_REQUEST).body(errorMessage);
    }
}

注意:为了使上述两种实现正常工作,您需要在application.properties文件中添加以下行。

spring.jackson.deserialization.fail-on-unknown-properties=true

希望这会对您有所帮助:)

答案 1 :(得分:0)

您需要配置ObjectMapper来处理此类情况:

objectMapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, true);

答案 2 :(得分:0)

或者您可以使用

导入com.fasterxml.jackson.annotation.JsonIgnoreProperties;

@JsonIgnoreProperties(ignoreUnknown =假) 公共类GetData {

}