To figure out how spring dispatcher servlet works, I make some breakpoints and debug my spring project. However, I found some results are not what I excepted. Below are the code
// controller code
@RestController
public class HelloController {
@RequestMapping("/dev/test")
public Map<String, Object> hello() {
Map<String, Object> result = new HashMap<>();
result.put("key", "value");
return result;
}
}
// interceptor
public class MyInterceptor extends HandlerInterceptorAdapter {
@Override
public boolean preHandle(HttpServletRequest request, HttpServletResponse response,
Object handler) throws Exception {
return true;
}
@Override
public void postHandle(
HttpServletRequest request,
HttpServletResponse response,
Object handler,
ModelAndView modelAndView)
throws Exception {
System.out.println("check here");
throw new RuntimeException("exception in myinterceptor"); // I intentionally throws exception here
}
}
// global exception handler
@ControllerAdvice
public class MyExceptionHandler {
@ResponseBody
@ExceptionHandler
public String handleException(Throwable throwable) {
System.out.println("throwable is " + throwable);
return "aaa";
}
}
The result is {"key":"value"}aaa
This is quite strange on the first look, but I can understand since controller successfully returns and may have written the {"key":"value"} part into outputBuffer. When dispatcher servlet execute interceptor post handle, a RuntimeException is thrown, so myExceptionHandler is called. Exception handler returns aaa, and it is also written to the outputBuffer. I personally think the corrected result should only contains the aaa part, which means the outputBuffer (contents are {"key":"value"}) should be cleared before aaa is written.
I wonder if the behavior is corrected or is this a bug. Thanks
Comment From: rstoyanchev
Thanks for getting in touch, but it feels like this is a question that would be better suited to Stack Overflow. As mentioned in the guidelines for contributing, we prefer to use the issue tracker only for bugs and enhancements. Feel free to update this issue with a link to the re-posted question (so that other people can find it) or add some more details if you feel this is a genuine bug.
Comment From: rstoyanchev
Note that the response commits automatically when the output buffer is full and therefore it cannot be cleared reliably. See Javadoc of HttpServletResponse#resetBuffer
.