簡體   English   中英

Java / Spring>在請求中未發送任何正文時,使用@RequestBody處理控制器方法的錯誤請求響應

[英]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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM