springboot用@Valid验证参数失败, 如何自定义返回给前端的json啊

一个简单的controller如下: 需要验证 helloVo 这个参数

    @RequestMapping(value = "/hello2", method = RequestMethod.GET)
    public JsonResult<MyMsg> hello2(@Valid HelloVo helloVo) {//...}

当我前台输入错误的参数后, 验证失败, 后台无异常信息, 原因是官方错将其设置为了DEBUG级别, 我觉得起码应该是WARN吧

日志如下:

[http-nio-8081-exec-1] DEBUG o.s.w.s.m.m.a.ServletInvocableHandlerMethod - Failed to resolve argument 0 of type 'com.surdoc.biz.sample.vo.HelloVo' 
org.springframework.validation.BindException: org.springframework.validation.BeanPropertyBindingResult: 1 errors
Field error in object 'helloVo' on field 'age': rejected value [2222]; codes [Max.helloVo.age,Max.age,Max.int,Max]; arguments [org.springframework.context.support.DefaultMessageSourceResolvable: codes [helloVo.age,age]; arguments []; default message [age],100]; default message [年龄不能大于100岁]
    at org.springframework.web.method.annotation.ModelAttributeMethodProcessor.resolveArgument(ModelAttributeMethodProcessor.java:118)
    at org.springframework.web.method.support.HandlerMethodArgumentResolverComposite.resolveArgument(HandlerMethodArgumentResolverComposite.java:121)
    at org.springframework.web.method.support.InvocableHandlerMethod.getMethodArgumentValues(InvocableHandlerMethod.java:158)
    at org.springframework.web.method.support.InvocableHandlerMethod.invokeForRequest(InvocableHandlerMethod.java:128)
    at org.springframework.web.servlet.mvc.method.annotation.ServletInvocableHandlerMethod.invokeAndHandle(ServletInvocableHandlerMethod.java:116)
    at org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.invokeHandlerMethod(RequestMappingHandlerAdapter.java:827)
    at org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.handleInternal(RequestMappingHandlerAdapter.java:738)
    at org.springframework.web.servlet.mvc.method.AbstractHandlerMethodAdapter.handle(AbstractHandlerMethodAdapter.java:85)
    at org.springframework.web.servlet.DispatcherServlet.doDispatch(DispatcherServlet.java:963)
    at org.springframework.web.servlet.DispatcherServlet.doService(DispatcherServlet.java:897)
    at org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:970)
    at org.springframework.web.servlet.FrameworkServlet.doGet(FrameworkServlet.java:861)
    at javax.servlet.http.HttpServlet.service(HttpServlet.java:622)
    at org.springframework.web.servlet.FrameworkServlet.service(FrameworkServlet.java:846)
    at javax.servlet.http.HttpServlet.service(HttpServlet.java:729)
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:230)

前台返回的json是如下这样, 我想自定义一下, 如何处理呢

{
    "timestamp": 1487311014043,
    "status": 400,
    "error": "Bad Request",
    "exception": "org.springframework.validation.BindException",
    "errors": [
        {
            "codes": [
                "Max.helloVo.age",
                "Max.age",
                "Max.int",
                "Max"
            ],
            "arguments": [
                {
                    "codes": [
                        "helloVo.age",
                        "age"
                    ],
                    "arguments": null,
                    "defaultMessage": "age",
                    "code": "age"
                },
                100
            ],
            "defaultMessage": "年龄不能大于100岁",
            "objectName": "helloVo",
            "field": "age",
            "rejectedValue": 2222,
            "bindingFailure": false,
            "code": "Max"
        }
    ],
    "message": "Validation failed for object='helloVo'. Error count: 1",
    "path": "/yunpan/sample/hello2"
}
阅读 26.7k
4 个回答

@Valid 的那个参数后面紧跟着一个 BindingResult 的参数(一定要紧跟着)

    @RequestMapping(value = "/hello2", method = RequestMethod.GET)
    public JsonResult<MyMsg> hello2(@Valid HelloVo helloVo, BindingResult bindingResult) {
        if (bindingResult.hasErrors()) {
            // 错误处理 (抛出异常交给全局处理或者在这里返回自定义的 JSON)
        }
    }

使用 @ControllerAdvice 处理全局异常

可以使用 @ControllerAdvice 配合 @ExceptionHandler来处理。

@ControllerAdvice
public class ExceptionControllerAdvice {
    @ExceptionHandler(BindException.class)
    public YourResultObject bindExceptionHandler(BindException ex){         
         // ...
         解析这个异常,然后包装成你想要的数据,就可以返回到前台了
         // ...
        return YourResultObject;
    }
}

BindingResult

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题
宣传栏