Spring Error handling MVC request body

When using @RequestBody StreamSource it turned out that if the xml in the request object is invalid, the StreamSource throws an exception (the result is 400 Bad Request), and I cannot process it (tell the client what is bad).

Is there a way to handle such an exception?

+6
source share
1 answer

In general, you can catch an exception in Spring MVC as follows:

 @ExceptionHandler(Exception.class) public ModelAndView handleMyException(Exception exception) { ModelAndView modelAndView = new ModelAndView("/errors/404"); modelAndView.addObject("message", exception.getMessage()); return modelAndView; } 

You can match it with any exception time and redirect the user to any page with any messages.

Alternatively: you can return it to @ResponseBody :

  @ExceptionHandler(Exception.class) @ResponseBody public String handleMyException(Exception exception) { return exception.getMessage(); } 
+10
source

Source: https://habr.com/ru/post/889374/


All Articles