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

前端 未结 2 532
悲哀的现实
悲哀的现实 2021-01-12 11:53

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

@RequestMapping(method = POST)
@ResponseBody
public Fo         


        
相关标签:
2条回答
  • 2021-01-12 12:47
    @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.

    0 讨论(0)
  • 2021-01-12 12:48

    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.

    0 讨论(0)
提交回复
热议问题