【发布时间】:2018-10-16 14:42:29
【问题描述】:
我们有一个基于 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"]}
如何轻松地进一步自定义?
【问题讨论】:
-
您可以添加您当前的响应和预期响应吗?
-
在您的 ApiError 对象中不要发送异常消息,因为这是实际抛出的错误消息。而不是发送自定义错误消息字符串,例如“请求中有未知属性,请检查 API 合同以了解详细信息”
-
感谢您对此进行调查。毕竟这并不太难。
标签: spring-boot spring-restcontroller