10

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;
    }
}
K Everest
  • 1,565
  • 5
  • 15
  • 23

2 Answers2

16

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.

skaffman
  • 398,947
  • 96
  • 818
  • 769
  • 4
    He could even use `throw new BindException(bindingResult)` and then have handler for BindException. – Adam Gent Aug 21 '12 at 13:41
  • 5
    He shouldn't even have to explicitly throw a `BindException`. Just remove the `BindingResult` argument from the method and spring will throw a `BindException` if there are any validation errors. And the exception handler method can access all the error details because `BindException` implements `BindingResult` and `Errors`. – JCoster22 May 15 '16 at 05:48
5
@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.

valar morghulis
  • 2,007
  • 27
  • 34
Albert Pinto
  • 392
  • 2
  • 6
  • 17
  • 1
    This will not work since there is already handler method for MethodArgumentNotValidException defined in ResponseEntityExceptionHandler, check this asnwer for further details, https://stackoverflow.com/a/38282563/4184240 – ahmedjaad Jul 13 '18 at 15:07