Java/Spring > 处理控制器方法的错误请求响应,当请求中没有发送正文时,@RequestBody



长话短说:我正在创建应该是100%休息的API。我正在尝试覆盖以下情况的默认响应:我的@RestController中有一个方法,该方法将@requestbody作为属性

@RequestMapping(value = {"register"}, method = RequestMethod.POST, produces = "application/hal+json")
public Resource<User> registerClient(@RequestBody User user, HttpServletRequest request)

,如果我发送适当的请求,该方法正常工作。但是当我不这样做时,有一个问题。当请求有空的身体时,我将获得一个通用的tomcat错误页面,以适用于状态400,我需要它仅发送一个字符串或JSON对象。

到目前为止,我试图在我的RestControllerAdvice中添加异常处理程序。

我已经知道,对于某些与安全有关的错误,必须在配置中创建处理程序,但是我不知道是否是这种情况。

有人面临类似问题吗?我缺少什么吗?

解决方案是简单地将 quirop = false = false 放入 requestbody 注释中。之后,我可以轻松地添加一些逻辑来投掷自定义异常并在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用作邮政通话的参数,并检查是否返回错误。

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

其次,呼叫可能会引发一些错误,一个好习惯是驾驶它们并将其归还或将其转换为您自己的异常对象。优势是它可以确保所有更新/修改方法的调用(帖子,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中添加一些注释,以避免在删除序列化时避免任何未知字段。

最新更新