在我的上一个项目中,当请求体包含额外参数时,需要抛出异常。
如果请求会是这样
{
"test":"body",
"name":"HR 1",
"location":"Location"
}
其中测试参数是不必要的,我必须返回一个应该像这样的响应
{
"timestamp": "2022-05-07T00:13:59.144657",
"status": "500",
"error": "Internal Server Error",
"message": "test : must not be provided",
"path": "/api/departments/HR"
}
我已经分享了答案。我是如何处理的。
最佳答案
我在 application.properties 中添加了这一行。
spring.jackson.deserialization.fail-on-unknown-properties=true
这有助于我们使反序列化在未知属性上失败并抛出一个我们可以使用 handleHttpMessageNotReadable 处理的异常
创建 Controller 通知来处理异常
@ControllerAdvice
public class CustomExceptionHandler extends ResponseEntityExceptionHandler {
@Override
protected ResponseEntity<Object> handleHttpMessageNotReadable(HttpMessageNotReadableException ex, HttpHeaders headers, HttpStatus status, WebRequest request) {
return new ResponseEntity("Your Response Object", HttpStatus.INTERNAL_SERVER_ERROR);
}
}
这就是解决方案。
关于java - spring boot请求体中有额外参数时如何抛出异常,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/72146456/