Spring Boot Rest API-未知字段-错误消息自定义

时间:2018-10-16 14:42:30

标签: spring-boot spring-restcontroller

我们有一个基于spring boot的rest api,它接受json中来自多个使用者的http post请求。它不能接受具有未知字段的请求,并且需要给出一个响应,指出这是一个错误的请求,并有意义地描述了错误。但是,出于安全原因,我们只需要向他们提供足够的错误信息

这是我们到目前为止的内容:

要实现这一目标,这是我们到目前为止所做的:

应用程序属性文件具有以下内容:
spring.jackson.deserialization.fail-on-unknown-properties=true

像这样自定义了异常处理(为简便起见,省略了其他功能):

@ControllerAdvice
@Order(Ordered.HIGHEST_PRECEDENCE)
public class RestExceptionHandler extends ResponseEntityExceptionHandler {

    Logger logger = LoggerFactory.getLogger(RestExceptionHandler.class);

    @Override
    public ResponseEntity<Object> handleHttpMessageNotReadable(
            HttpMessageNotReadableException ex, HttpHeaders headers, HttpStatus status, WebRequest request) {

        //this message can't give them info about known properties
        exceptionMessage = ex.getLocalizedMessage();
        logger.debug("exceptionMessage: " + ex.getLocalizedMessage());

        //ApiError is a custom object to encapsulate the information to be sent in the api response.
        ApiError apiError = new ApiError(HttpStatus.BAD_REQUEST, "HTTP message not readable", exceptionMessage);
        apiError.setHttpStatus(HttpStatus.BAD_REQUEST);
        apiError.setErrorMessage(errorMessage);

        return new ResponseEntity<Object>(apiError, new HttpHeaders(), apiError.getHttpStatus());
    }
}

包含unknown-field的json请求将导致以下异常:

com.fasterxml.jackson.databind.exc.UnrecognizedPropertyException: Unrecognized field "unknown-field" (class mypackage.MyDomain), not marked as ignorable (2 known properties: "known-field-1", "known-field-2"])

出于安全原因(2 known properties: "known-field-1", "known-field-2"]),我们不想提供有关已知属性的详细信息。

请求正文:

{"known-field-1": 1, "unknown-field": 2}

实际响应正文:

{"status":"BAD_REQUEST","message":"HTTP message not readable","errors":[Unrecognized field "unknown-field" (class mypackage.MyDomain), not marked as ignorable (2 known properties: "known-field-1", "known-field-2"]}

所需的响应正文:

{"status":"BAD_REQUEST","message":"HTTP message not readable","errors":["Unknown field: unknown-field"]}

如何进一步轻松自定义此内容?

1 个答案:

答案 0 :(得分:0)

这解决了它:

@Override
public ResponseEntity<Object> handleHttpMessageNotReadable(
        HttpMessageNotReadableException ex, HttpHeaders headers, HttpStatus status, WebRequest request) {

    String exceptionMessage = null;

    Throwable rootCause = ex.getRootCause();
    if(rootCause instanceof UnrecognizedPropertyException)
    {
        exceptionMessage = "Unknown field: " + ((UnrecognizedPropertyException) rootCause).getPropertyName();
        logger.debug("exceptionMessage: " + exceptionMessage);
    }

    ApiError apiError = 
      new ApiError(HttpStatus.BAD_REQUEST, "HTTP message not readable", exceptionMessage);

    return new ResponseEntity<Object>(apiError, new HttpHeaders(), apiError.getStatus());
}