如何在RESTful Spring MVC控制器中处理验证错误和异常?

K E*_*est 5 java rest spring spring-mvc

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

@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;
    }
}
Run Code Online (Sandbox Code Playgroud)

ska*_*man 14

如果出现错误则抛出异常,然后用于@ExceptionHandler注释另一个方法,该方法将处理异常并呈现相应的响应.

  • 他甚至可以使用`throw new BindException(bindingResult)`然后使用BindException的处理程序. (2认同)
  • 他甚至不必显式抛出`BindException`.只需从方法中删除`BindingResult`参数,如果有任何验证错误,spring将抛出`BindException`.异常处理程序方法可以访问所有错误细节,因为`BindException`实现了`BindingResult`和`Errors`. (2认同)

Alb*_*nto 5

@RequestMapping(method = POST)
@ResponseBody
public FooDto create(@Valid FooDTO fooDto) {
//Do my business logic here
    return fooDto;

}
Run Code Online (Sandbox Code Playgroud)

创建一个异常处理程序:

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

    return formatException(objException);
}
Run Code Online (Sandbox Code Playgroud)

我不知道这是我遵循的正确方法。如果您能告诉我您对这个问题所做的工作,将不胜感激。