SpringMVC 捕获参数绑定失败时的异常

 

SpringMVC配置数据验证(JSR-303)中提到了用String类型的域来绑定Ajax中的非法类型的参数。

这样做的目的是一旦发生一种情况,后端可以返回一个自定类的返回值,而不是返回SpringMVC参数绑定失败的错误信息。

但是,这样做并不OOP。

 

更好的方法是使用@ControllerAdvice和@ExceptionHandler标签来捕获参数绑定失败的异常,如下

@ControllerAdvice
public class InputExceptionHandler {

    @ExceptionHandler(HttpMessageNotReadableException.class)
    @ResponseStatus(HttpStatus.OK)
    @ResponseBody
    public void httpMessageNotReadableException(HttpMessageNotReadableException e) {
        return RequestResult.failure("请求不可读(可能原因:1.没有Request Body 2.Request Body格式有误)");
    }

}

 

这样一来,Input类中的域就不需要为了容错而定义成String类型了。

 

posted @ 2017-12-06 10:49  Deolin  阅读(977)  评论(0编辑  收藏  举报