[英]Java/Spring > Handle Bad Request response for controller method with @RequestBody when no body is sent in request
长话短说:我正在创建应该100%REST的API。 我正在尝试覆盖以下情况的默认响应:我的@RestController中有一个方法,该方法具有@RequestBody作为属性
@RequestMapping(value = {"register"}, method = RequestMethod.POST, produces = "application/hal+json")
public Resource<User> registerClient(@RequestBody User user, HttpServletRequest request)
如果我发送适当的请求,该方法就可以正常工作。 但是,如果我不这样做,就会有问题。 当请求的主体为空时,我得到状态为400的通用Tomcat错误页面,我需要它仅发送字符串或JSON对象。
到目前为止,我已经尝试在org.springframework.web.binding包中的所有Spring异常的RestControllerAdvice中添加异常处理程序,但是它也不起作用。
我已经知道,对于某些与安全性相关的错误,必须在配置中创建处理程序,但是我不知道是否是这种情况。
有没有人遇到类似的问题? 有什么我想念的吗?
解决方案是在RequestBody批注中简单地将required = false 放入 。 之后,我可以轻松添加一些逻辑以引发自定义异常并在ControllerAdvice中对其进行处理。
@RequestMapping(value = {"register"}, method = RequestMethod.POST, produces = "application/hal+json")
public Resource<User> registerClient(@RequestBody(required = false) User user, HttpServletRequest request){
logger.debug("addClient() requested from {}; registration of user ({})", getClientIp(request), user);
if(user == null){
throw new BadRequestException()
.setErrorCode(ErrorCode.USER_IS_NULL.toString())
.setErrorMessage("Wrong body or no body in reqest");
} (...)
首先,我建议您将BindingResult
用作POST调用的参数,并检查它是否返回错误。
@RequestMapping(value = {"register"}, method = RequestMethod.POST, produces = "application/hal+json")
public ResponseEntity<?> registerClient(@RequestBody User user, HttpServletRequest request, BindingResult brs)
if (!brs.hasErrors()) {
// add the new one
return new ResponseEntity<User>(user, HttpStatus.CREATED);
}
return new ResponseEntity<String>(brs.toString(), HttpStatus.BAD_REQUEST);
}
其次,该调用可能会引发一些错误,一个好的做法是将其保留并返回它们本身或将其转换为您自己的异常对象。 好处是它可以确保所有更新/修改方法(POST,PUT,PATCH)的调用
@ExceptionHandler(MethodArgumentNotValidException.class)
@ResponseBody
public ResponseEntity<?> handleMethodArgumentNotValidException(MethodArgumentNotValidException e) {
return new ResponseEntity<List<MethodArgumentNotValidException>>(e, HttpStatus.BAD_REQUEST);
}
@ExceptionHandler({HttpMessageNotReadableException.class})
@ResponseBody
public ResponseEntity<?> handleHttpMessageNotReadableException(HttpMessageNotReadableException e) {
return new ResponseEntity<List<HttpMessageNotReadableException>>(e, HttpStatus.BAD_REQUEST);
}
在正常情况下,您的控件将永远无法达到您的请求方法。 如果您希望页面看起来不错,可以使用web.xml
并将其配置为产生答案。
<error-page>
<error-code>404</error-code>
<location>/pages/resource-not-found.html</location>
</error-page>
通常,如果您想解决此400问题,则必须在User.java
添加一些注释,以避免在反序列化时出现任何未知字段。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.