例如,如何在此控制器操作方法中处理验证错误和可能的异常:
@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;
}
}
答案 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);
}
我不知道这是否是我所遵循的正确方法。如果你能告诉我你为这个问题做了什么,我将不胜感激。