Warning: file_get_contents(/data/phpspider/zhask/data//catemap/5/spring-mvc/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
如何在对spring restapi的json请求中的未知字段上抛出错误_Spring_Spring Mvc_Spring Boot_Jackson_Spring Rest - Fatal编程技术网

如何在对spring restapi的json请求中的未知字段上抛出错误

如何在对spring restapi的json请求中的未知字段上抛出错误,spring,spring-mvc,spring-boot,jackson,spring-rest,Spring,Spring Mvc,Spring Boot,Jackson,Spring Rest,我有一个springrestapi,它获取json数据并绑定到pojogetdata。 每当我收到未知字段时,它不会失败或抛出任何异常。我的要求是,当它接收到json数据中的未知字段时,它应该抛出一个错误 public ResponseEntity<Error> saveLocation(@Valid @RequestBody GetData getdata,BindingResult bindingResults) { 下面是我的json请求 { "deviceID" : "01

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

public ResponseEntity<Error> saveLocation(@Valid @RequestBody GetData getdata,BindingResult bindingResults) {
下面是我的json请求

{
"deviceID" : "01dbd619-843b-4197-b954",
"Coordinates" : "12.984012,80.246712",
}
现在,如果我发送一个带有额外字段的请求,请输入country。它不会抛出任何错误

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

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

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

objectMapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, true);

您可以尝试下面的任何一种实现,它对我很有用。您必须从
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
}
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);
    }
}
2。使用ExceptionHandler

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
}
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);
    }
}

希望这对您有所帮助:)

或者您可以使用:

import com.fasterxml.jackson.annotation.JsonIgnoreProperties;

@JsonIgnoreProperties(ignoreUnknown = false)
public class GetData {

}

@user3341233这对您有帮助吗?但是如何在纯Spring MVC(非Spring Boot)应用程序中获得
objectMapper
实例?@dbreaux它是一个
Bean
。如何从spring上下文中获取任何bean?我想
@Autowired
它,但在这种情况下,我尝试这样做时没有得到任何对象。(我实际上问了一个新问题)
import com.fasterxml.jackson.annotation.JsonIgnoreProperties;

@JsonIgnoreProperties(ignoreUnknown = false)
public class GetData {

}