SpringMVC中@RequestBody引起的400異常處理,返回校驗失敗具體信息


問題

使用@RequestBody接收一個json數據的時候,如果傳入的參數不符合條件,就會直接返回400的error page. 但究竟是為什么會400並沒有拋出來。這對大量參數字段的我們來說,排錯很困難,所以應該返回出錯的原因。

Resolve

This was raised as an issue with Spring SPR-7439 - JSON (jackson) @RequestBody marshalling throws awkward exception - which was fixed in Spring 3.1M2 by having Spring throw a org.springframework.http.converter.HttpMessageNotReadableException in the case of a missing or invalid message body.

以上來自stackoverflow.

具體就是當spring的@RequestBody注解進行marshall操作的時候,如果jackson跑出異常,就會拋出一個叫做HttpMessageNotReadableException的異常,那么我們只要捕獲並返回這個異常就可以了。

具體做法

最簡單是在controller里加一個錯誤處理的方案:

@ExceptionHandler({HttpMessageNotReadableException.class})
@ResponseStatus(HttpStatus.BAD_REQUEST)
@ResponseBody
public CodeMsg resolveException(HttpMessageNotReadableException errors) {

	return CodeMsg.error(errors.getMessage());
}

如果想要對所有的controller生效,那么需要一個注解@ControllerAdvice:


@ControllerAdvice
public class GeneralHandler {

   @ExceptionHandler
   public ModelAndView handleException (NoSuchRequestHandlingMethodException ex) {
        ModelAndView mav = new ModelAndView();
        ...
        return mav;
   }
}

所以,可以處理你想要的異常:


@ExceptionHandler
@ResponseBody
@ResponseStatus(HttpStatus.BAD_REQUEST)
public RestError resolveBindingException ( MethodArgumentNotValidException methodArgumentNotValidException, Locale locale )
{
    BindingResult bindingResult = methodArgumentNotValidException.getBindingResult();
    return getRestError(bindingResult, locale);
}


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM