【问题标题】:MethodArgumentNotValidException not thrown未抛出 MethodArgumentNotValidException
【发布时间】:2014-05-14 00:44:44
【问题描述】:

我的控制器如下所示:

@RequestMapping(value = "/cars/{types}", method = RequestMethod.PUT,
        headers = "Accept=application/json")
@ResponseStatus(HttpStatus.OK)
public void startEngine(
        @PathVariable @Min(0) String types, @RequestBody @Valid someObject request, BindingResult result)
        throws MethodArgumentNotValidException {

    if(result.hasErrors())
    {
        System.out.println("Error");
        //Should I be throwing MethodArgumentNotValidException here? And if so how? I don't know how to retrieve the first parameter for it's constructor (MethodParameter object)
    }
    //Controller code
}

所以在我验证我的结果对象在验证期间是否遇到任何错误之后,我该如何抛出 MethodArgumentNotValidException?或者 Spring 是否应该在验证期间已经抛出该异常?

【问题讨论】:

    标签: java spring validation


    【解决方案1】:

    如果我没记错的话,Spring 应该抛出MethodArgumentNotValidException 只有如果你没有为@Valid 注释参数提供Errors(这里是BindingResult)参数。

    如果你愿意,你可以自己扔。

    【讨论】:

    • @user1553248 在你这样做之前,我会检查我所说的是否属实。我现在没有一台装有 Spring 的机器来测试它。
    • 我有,我选择删除 BindingResult 对象实际上是解决我的问题的更好方法,现在 Spring 正在适当地抛出 MethodArgumentNotValidExceptions。
    • 你知道如何抛出 MethodArgumentNotValidException 吗?检索与错误字段相关的方法参数很困难。
    • @user1553248 看到这一点,您可能应该抛出一个自定义异常。
    • 它仍然不适合我。我在 ControllerAdvice 中扩展了 ResponseEntityExceptionHandler,并在那里重写了方法 handleMethodArgumentNotValid。在这里,我想返回自定义错误消息,但它不起作用。 Spring 正在抛出默认消息结构。
    猜你喜欢
    • 1970-01-01
    • 2014-06-06
    • 1970-01-01
    • 1970-01-01
    • 2011-04-02
    • 1970-01-01
    • 2020-05-19
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多