Reputation: 1585
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;
}
}
Upvotes: 11
Views: 31974
Reputation: 402
@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.
Upvotes: 6
Reputation: 403451
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.
Upvotes: 16