ExceptionHandlerExceptionResolver
代码参考
点击查看代码
public static void main(String[] args) throws NoSuchMethodException {
ExceptionHandlerExceptionResolver resolver = new ExceptionHandlerExceptionResolver();
resolver.setMessageConverters(List.of(new MappingJackson2HttpMessageConverter()));
resolver.afterPropertiesSet();
MockHttpServletRequest request = new MockHttpServletRequest();
MockHttpServletResponse response = new MockHttpServletResponse();
// // 1.测试 json
// HandlerMethod handlerMethod = new HandlerMethod(new Controller1(), Controller1.class.getmethod("foo"));
// Exception e = new ArithmeticException("被零除");
// resolver.resolveException(request, response, handlerMethod, e);
// System.out.println(new String(response.getContentAsByteArray(), StandardCharsets.UTF_8));
// // 2.测试 mav
// HandlerMethod handlerMethod = new HandlerMethod(new Controller2(), Controller2.class.getmethod("foo"));
// Exception e = new ArithmeticException("被零除");
// ModelAndView mav = resolver.resolveException(request, response, handlerMethod, e);
// System.out.println(mav.getModel());
// System.out.println(mav.getViewName());
// // 3.测试嵌套异常
// HandlerMethod handlerMethod = new HandlerMethod(new Controller3(), Controller3.class.getmethod("foo"));
// Exception e = new Exception("e1", new RuntimeException("e2", new IOException("e3")));
// resolver.resolveException(request, response, handlerMethod, e);
// System.out.println(new String(response.getContentAsByteArray(), StandardCharsets.UTF_8));
// 4.测试异常处理方法参数解析
HandlerMethod handlerMethod = new HandlerMethod(new Controller4(), Controller4.class.getmethod("foo"));
Exception e = new Exception("e1");
resolver.resolveException(request, response, handlerMethod, e);
System.out.println(new String(response.getContentAsByteArray(), StandardCharsets.UTF_8));
static class Controller1 {
public void foo() {
}
@ExceptionHandler
@ResponseBody
public Map<String, Object> handle(ArithmeticException e) {
return Map.of("error", e.getMessage());
}
}
static class Controller2 {
public void foo() {
}
@ExceptionHandler
public ModelAndView handle(ArithmeticException e) {
return new ModelAndView("test2", Map.of("error", e.getMessage()));
}
}
static class Controller3 {
public void foo() {
}
@ExceptionHandler
@ResponseBody
public Map<String, Object> handle(IOException e3) {
return Map.of("error", e3.getMessage());
}
}
static class Controller4 {
public void foo() {}
@ExceptionHandler
@ResponseBody
public Map<String, Object> handler(Exception e, HttpServletRequest request) {
System.out.println(request);
return Map.of("error", e.getMessage());
}
}
小结
- 它能够重用参数解析器、返回值处理器,实现组件重用
- 它能够支持嵌套异常
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 [email protected] 举报,一经查实,本站将立刻删除。