【问题标题】:How to handle validation errors and exceptions in a RESTful Spring MVC controller?如何在 RESTful Spring MVC 控制器中处理验证错误和异常?
【发布时间】:2012-03-03 23:13:12
【问题描述】:

例如,如何处理这个控制器动作方法中的验证错误和可能的异常:

@RequestMapping(method = POST)
@ResponseBody
public FooDto create(@Valid FooDTO fooDto, BindingResult bindingResult) {
    if (bindingResult.hasErrors()) {
        return null; // what to do here?
                     // how to let the client know something has gone wrong?
    } else {
        fooDao.insertFoo(fooDto); // What to do if an exception gets thrown here?
                                  // What to send back to the client?
        return fooDto;
    }
}

【问题讨论】:

  • 发回适当的错误响应和/或代码。我想我不明白这个问题。
  • 该操作返回一个FooDTO,如何返回带有一些验证错误消息的适当响应?

标签: java spring rest spring-mvc


【解决方案1】:
@RequestMapping(method = POST)
@ResponseBody
public FooDto create(@Valid FooDTO fooDto) {
//Do my business logic here
    return fooDto;

}

创建一个异常处理程序:

@ExceptionHandler( MethodArgumentNotValidException.class)
@ResponseBody
@ResponseStatus(value = org.springframework.http.HttpStatus.BAD_REQUEST)
protected CustomExceptionResponse handleDMSRESTException(MethodArgumentNotValidException objException)
{

    return formatException(objException);
}

我不知道这是否是我遵循的正确方法。如果你能告诉我你为这个问题做了什么,我将不胜感激。

【讨论】:

  • 这将不起作用,因为在 ResponseEntityExceptionHandler 中已经定义了 MethodArgumentNotValidException 的处理程序方法,请查看此 asnwer 以获取更多详细信息,stackoverflow.com/a/38282563/4184240
【解决方案2】:

如果出现错误则抛出异常,然后使用@ExceptionHandler to annotate another method 处理异常并呈现适当的响应。

【讨论】:

  • 他甚至可以使用throw new BindException(bindingResult),然后处理BindException。
  • 他甚至不应该明确地抛出BindException。只需从方法中删除BindingResult 参数,如果有任何验证错误,spring 将抛出BindException。并且异常处理方法可以访问所有错误细节,因为BindException 实现了BindingResult 和Errors。
猜你喜欢
  • 2017-12-11
  • 1970-01-01
  • 2016-11-06
  • 2017-11-23
  • 1970-01-01
  • 2016-04-16
  • 2020-04-09
  • 1970-01-01
  • 2012-12-14
相关资源
最近更新 更多