How to handle validation errors and exceptions in a RESTful Spring MVC controller?

感情迁移 提交于 2019-12-01 03:10:23

问题


For example, how to handle validation errors and possible exceptions in this controller action method:

@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;
    }
}

回答1:


Throw an exception if you have an error, and then use @ExceptionHandler to annotate another method which will then handle the exception and render the appropriate response.




回答2:


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

}

Create a n exception handler:

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

    return formatException(objException);
}

I don't know if this is the correct approach i am following. I would appreciate if you could tell me what you have done for this issue.



来源:https://stackoverflow.com/questions/9245487/how-to-handle-validation-errors-and-exceptions-in-a-restful-spring-mvc-controlle

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!