spring写入中断响应,因为侦听器异常

qeeaahzv  于 2021-07-13  发布在  Java
关注(0)|答案(0)|浏览(201)

为了弄清楚springdispatcherservlet是如何工作的,我设置了一些断点并调试了spring项目。然而,我发现有些结果并不例外。下面是代码

// 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";
    }
}

结果是 {"key":"value"}aaa .
这在第一眼看上去很奇怪,但是我可以理解,因为控制器成功地返回,并且可能已经编写了 {"key":"value"} 输入输出缓冲区。当dispatcherservlet执行interceptor post handle时,抛出runtimeexception,因此调用myexceptionhandler。异常处理程序返回 aaa ,并将其写入outputbuffer。我个人认为正确的结果应该只包含 aaa 部分,这意味着输出缓冲区(内容是 {"key":"value"} )应该在 aaa 是这样写的。
我想知道这种行为是否得到纠正。谢谢

暂无答案!

目前还没有任何答案,快来回答吧!

相关问题