Spring -MVC exception handler returns OK when writing to the response

I am using spring -webmvc: 3.2.3.RELEASE (and its related dependencies).

I have this controller:

@Controller @RequestMapping("/home") public class HomeController { @Autowired MappingJacksonHttpMessageConverter messageConverter; @RequestMapping(method = RequestMethod.GET) public String get() { throw new RuntimeException("XXXXXX"); } @ExceptionHandler(value = java.lang.RuntimeException.class) @ResponseStatus(HttpStatus.CONFLICT) public ModelAndView runtimeExceptionAndView(ServletWebRequest webRequest) throws Exception { ModelAndView retVal = handleResponseBody("AASASAS", webRequest); return retVal; } @SuppressWarnings({ "resource", "rawtypes", "unchecked" }) private ModelAndView handleResponseBody(Object body, ServletWebRequest webRequest) throws ServletException, IOException { ServletServerHttpResponse outputMessage = new ServletServerHttpResponse(webRequest.getResponse()); messageConverter.write(body, MediaType.APPLICATION_JSON, outputMessage); return new ModelAndView(); } } 

since the / home method throws a RuntimeException that is thrown with @ExceptionHandler when the get () method is called, I expect to get HttpStatus.CONFLICT, but instead I get HttpStatus.OK. Can someone please tell me What should I do to get the response status from the processed annotation handler?

+4
source share
2 answers

The reason is because you are explicitly writing to the output stream, rather than letting it handle it. The header must go before the contents of the body are written, if you are explicitly processing the write to the output stream, you will also need to write a header.

To allow the structure to handle the entire stream, you can do this:

 @ExceptionHandler(value = java.lang.RuntimeException.class) @ResponseStatus(HttpStatus.CONFLICT) @ResponseBody public TypeToBeMarshalled runtimeExceptionAndView(ServletWebRequest webRequest) throws Exception { return typeToBeMarshalled; } 
+4
source

Change the ExceptionHandler method like this

 @ExceptionHandler(value = java.lang.RuntimeException.class) public ModelAndView runtimeExceptionAndView(ServletWebRequest webRequest, HttpServletResponse response) throws Exception { response.setStatus(HttpStatus.CONFLICT.value()); ModelAndView retVal = handleResponseBody("AASASAS", webRequest); return retVal; } 

If you want to handle json result exception, I suggest using @ResponseBody with Json auto-return.

 @ExceptionHandler(value = java.lang.RuntimeException.class) @ResponseBody public Object runtimeExceptionAndView(ServletWebRequest webRequest, HttpServletResponse response) throws Exception { response.setStatus(HttpStatus.CONFLICT.value()); return new JsonResult(); } 
+2
source

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


All Articles