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

时间:2012-02-12 00:55:18

标签: java spring rest 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;
    }
}

2 个答案:

答案 0 :(得分:14)

如果您遇到错误,请抛出异常,然后使用@ExceptionHandler to annotate another method然后处理异常并呈现相应的响应。

答案 1 :(得分:3)

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

}

创建一个n异常处理程序:

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

    return formatException(objException);
}

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