Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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;
    }
}
like image 216
K Everest Avatar asked Feb 12 '12 00:02

K Everest


People also ask

How do you handle authentication and exception handling in Spring Boot and Spring MVC applications?

Spring MVC Framework provides following ways to help us achieving robust exception handling. Controller Based - We can define exception handler methods in our controller classes. All we need is to annotate these methods with @ExceptionHandler annotation. This annotation takes Exception class as argument.


2 Answers

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.

like image 149
skaffman Avatar answered Oct 01 '22 18:10

skaffman


@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.

like image 31
Albert Pinto Avatar answered Oct 01 '22 19:10

Albert Pinto