Java源码示例:org.springframework.web.servlet.handler.HandlerExceptionResolverComposite

示例1
@Test
public void customArgumentResolvers() {
	ApplicationContext context = initContext(CustomArgumentResolverConfig.class);
	RequestMappingHandlerAdapter adapter = context.getBean(RequestMappingHandlerAdapter.class);
	HandlerExceptionResolverComposite composite = context.getBean(HandlerExceptionResolverComposite.class);

	assertNotNull(adapter);
	assertEquals(1, adapter.getCustomArgumentResolvers().size());
	assertEquals(TestArgumentResolver.class, adapter.getCustomArgumentResolvers().get(0).getClass());
	assertEquals(1, adapter.getCustomReturnValueHandlers().size());
	assertEquals(TestReturnValueHandler.class, adapter.getCustomReturnValueHandlers().get(0).getClass());

	assertNotNull(composite);
	assertEquals(3, composite.getExceptionResolvers().size());
	assertEquals(ExceptionHandlerExceptionResolver.class, composite.getExceptionResolvers().get(0).getClass());

	ExceptionHandlerExceptionResolver resolver =
			(ExceptionHandlerExceptionResolver) composite.getExceptionResolvers().get(0);

	assertEquals(1, resolver.getCustomArgumentResolvers().size());
	assertEquals(TestArgumentResolver.class, resolver.getCustomArgumentResolvers().get(0).getClass());
	assertEquals(1, resolver.getCustomReturnValueHandlers().size());
	assertEquals(TestReturnValueHandler.class, resolver.getCustomReturnValueHandlers().get(0).getClass());
}
 
示例2
@Test
public void configureExceptionResolvers() throws Exception {
	List<WebMvcConfigurer> configurers = new ArrayList<>();
	configurers.add(new WebMvcConfigurer() {
		@Override
		public void configureHandlerExceptionResolvers(List<HandlerExceptionResolver> exceptionResolvers) {
			exceptionResolvers.add(new DefaultHandlerExceptionResolver());
		}
	});
	delegatingConfig.setConfigurers(configurers);

	HandlerExceptionResolverComposite composite =
			(HandlerExceptionResolverComposite) delegatingConfig
					.handlerExceptionResolver(delegatingConfig.mvcContentNegotiationManager());
	assertEquals("Only one custom converter is expected", 1, composite.getExceptionResolvers().size());
}
 
示例3
/**
 * 动态添加异常切面
 * @param handlerExceptionResolver  HandlerExceptionResolver
 * @param beanFactory               BeanFactory
 * @param beanName                  异常拦截处理器bean名
 */
public static void addDynamicExceptionAdvice(HandlerExceptionResolver handlerExceptionResolver, BeanFactory beanFactory, String beanName) {
    if (handlerExceptionResolver instanceof HandlerExceptionResolverComposite) {
        List<HandlerExceptionResolver> exceptionResolvers = ((HandlerExceptionResolverComposite) handlerExceptionResolver).getExceptionResolvers();
        for (HandlerExceptionResolver exceptionResolver : exceptionResolvers) {
            if (exceptionResolver instanceof ExceptionHandlerExceptionResolver) {
                // TODO <mark> 由于使用底层API, 这个exceptionHandlerAdviceCache属性在未来版本中可能会改
                Map<ControllerAdviceBean, ExceptionHandlerMethodResolver> resolverMap = ReflectUtil.invokeFieldPath(exceptionResolver, "exceptionHandlerAdviceCache");
                if (resolverMap == null) {
                    resolverMap = new HashMap<>(2);
                }
                // 仿Spring MVC源码创建advice
                ControllerAdviceBean adviceBean = new ControllerAdviceBean(beanName, ApplicationContextHolder.get(), null);
                Class<?> beanType = adviceBean.getBeanType();
                if (beanType == null) {
                    throw new IllegalStateException("SpringMvcPolyfill find unresolvable type for ControllerAdviceBean: " + adviceBean);
                }
                ExceptionHandlerMethodResolver resolver = new ExceptionHandlerMethodResolver(beanType);
                if (resolver.hasExceptionMappings()) {
                    resolverMap.put(adviceBean, resolver);
                }
                break;
            }
        }
    }
}
 
示例4
@Test
public void customArgumentResolvers() {
	ApplicationContext context = initContext(CustomArgumentResolverConfig.class);
	RequestMappingHandlerAdapter adapter = context.getBean(RequestMappingHandlerAdapter.class);
	HandlerExceptionResolverComposite composite = context.getBean(HandlerExceptionResolverComposite.class);

	assertNotNull(adapter);
	assertEquals(1, adapter.getCustomArgumentResolvers().size());
	assertEquals(TestArgumentResolver.class, adapter.getCustomArgumentResolvers().get(0).getClass());
	assertEquals(1, adapter.getCustomReturnValueHandlers().size());
	assertEquals(TestReturnValueHandler.class, adapter.getCustomReturnValueHandlers().get(0).getClass());

	assertNotNull(composite);
	assertEquals(3, composite.getExceptionResolvers().size());
	assertEquals(ExceptionHandlerExceptionResolver.class, composite.getExceptionResolvers().get(0).getClass());

	ExceptionHandlerExceptionResolver resolver =
			(ExceptionHandlerExceptionResolver) composite.getExceptionResolvers().get(0);

	assertEquals(1, resolver.getCustomArgumentResolvers().size());
	assertEquals(TestArgumentResolver.class, resolver.getCustomArgumentResolvers().get(0).getClass());
	assertEquals(1, resolver.getCustomReturnValueHandlers().size());
	assertEquals(TestReturnValueHandler.class, resolver.getCustomReturnValueHandlers().get(0).getClass());
}
 
示例5
/**
 * Returns a {@link HandlerExceptionResolverComposite} containing a list of exception
 * resolvers obtained either through {@link #configureHandlerExceptionResolvers} or
 * through {@link #addDefaultHandlerExceptionResolvers}.
 * <p><strong>Note:</strong> This method cannot be made final due to CGLIB constraints.
 * Rather than overriding it, consider overriding {@link #configureHandlerExceptionResolvers}
 * which allows for providing a list of resolvers.
 */
@Bean
public HandlerExceptionResolver handlerExceptionResolver(
		ContentNegotiationManager mvcContentNegotiationManager) {
	List<HandlerExceptionResolver> exceptionResolvers = new ArrayList<>();
	configureHandlerExceptionResolvers(exceptionResolvers);
	if (exceptionResolvers.isEmpty()) {
		addDefaultHandlerExceptionResolvers(exceptionResolvers, mvcContentNegotiationManager);
	}
	extendHandlerExceptionResolvers(exceptionResolvers);
	HandlerExceptionResolverComposite composite = new HandlerExceptionResolverComposite();
	composite.setOrder(0);
	composite.setExceptionResolvers(exceptionResolvers);
	return composite;
}
 
示例6
@Test
public void exceptionResolvers() throws Exception {
	List<HandlerExceptionResolver> resolvers = ((HandlerExceptionResolverComposite)
			this.config.handlerExceptionResolver(null)).getExceptionResolvers();

	assertEquals(2, resolvers.size());
	assertEquals(ResponseStatusExceptionResolver.class, resolvers.get(0).getClass());
	assertEquals(SimpleMappingExceptionResolver.class, resolvers.get(1).getClass());
}
 
示例7
@Test
@SuppressWarnings("unchecked")
public void handlerExceptionResolver() throws Exception {
	ApplicationContext context = initContext(WebConfig.class);
	HandlerExceptionResolverComposite compositeResolver =
			context.getBean("handlerExceptionResolver", HandlerExceptionResolverComposite.class);

	assertEquals(0, compositeResolver.getOrder());
	List<HandlerExceptionResolver> expectedResolvers = compositeResolver.getExceptionResolvers();

	assertEquals(ExceptionHandlerExceptionResolver.class, expectedResolvers.get(0).getClass());
	assertEquals(ResponseStatusExceptionResolver.class, expectedResolvers.get(1).getClass());
	assertEquals(DefaultHandlerExceptionResolver.class, expectedResolvers.get(2).getClass());

	ExceptionHandlerExceptionResolver eher = (ExceptionHandlerExceptionResolver) expectedResolvers.get(0);
	assertNotNull(eher.getApplicationContext());

	DirectFieldAccessor fieldAccessor = new DirectFieldAccessor(eher);
	List<Object> interceptors = (List<Object>) fieldAccessor.getPropertyValue("responseBodyAdvice");
	assertEquals(1, interceptors.size());
	assertEquals(JsonViewResponseBodyAdvice.class, interceptors.get(0).getClass());

	LocaleContextHolder.setLocale(Locale.ENGLISH);
	try {
		ResponseStatusExceptionResolver rser = (ResponseStatusExceptionResolver) expectedResolvers.get(1);
		MockHttpServletRequest request = new MockHttpServletRequest("GET", "/");
		MockHttpServletResponse response = new MockHttpServletResponse();
		rser.resolveException(request, response, context.getBean(TestController.class), new UserAlreadyExistsException());
		assertEquals("User already exists!", response.getErrorMessage());
	}
	finally {
		LocaleContextHolder.resetLocaleContext();
	}
}
 
示例8
/**
 * 动态添加消息体响应切面
 * @param returnValueHandlers       响应处理器列表(需要注入 {@link org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter#getReturnValueHandlers()})
 * @param handlerExceptionResolver  异常处理解析器(需要注入 {@link org.springframework.web.servlet.HandlerExceptionResolver})
 * @param responseBodyAdvice        ResponseBodyAdvice
 */
public static void addDynamicResponseBodyAdvice(List<HandlerMethodReturnValueHandler> returnValueHandlers, HandlerExceptionResolver handlerExceptionResolver, ResponseBodyAdvice<?> responseBodyAdvice) {
    if (CollectionUtils.isEmpty(returnValueHandlers)) {
        return;
    }
    // 下面这行添加不起作用,由于内部构建已经完成
    // adapter.setResponseBodyAdvice(Collections.singletonList(responseBodyAdvice));
    for (HandlerMethodReturnValueHandler returnValueHandler : returnValueHandlers) {
        // 只有AbstractMessageConverterMethodArgumentResolver继承类型(主要是HttpEntityMethodProcessor、RequestResponseBodyMethodProcessor)有Advice Chain
        if (returnValueHandler instanceof AbstractMessageConverterMethodArgumentResolver) {
            // TODO <mark> 由于使用底层API, 这个advice.responseBodyAdvice属性在未来版本中可能会改
            List<Object> advices = ReflectUtil.invokeFieldPath(returnValueHandler, "advice.responseBodyAdvice");
            if (CollectionUtils.isEmpty(advices)) {
                continue;
            }
            advices.add(responseBodyAdvice);
        }
    }

    // 动态添加到异常处理(因为源码流程中的异常处理是新加载的HandlerExceptionResolver,与正常响应处理不是同个处理集)
    if (handlerExceptionResolver instanceof HandlerExceptionResolverComposite) {
        // SpringMVC默认为注册HandlerExceptionResolverComposite的Bean
        List<HandlerExceptionResolver> exceptionResolvers = ((HandlerExceptionResolverComposite) handlerExceptionResolver).getExceptionResolvers();
        if (CollectionUtils.isEmpty(exceptionResolvers)) {
            return;
        }
        for (HandlerExceptionResolver exceptionResolver : exceptionResolvers) {
            if (exceptionResolver instanceof ExceptionHandlerExceptionResolver) {
                HandlerMethodReturnValueHandlerComposite returnValueHandlerComposite = ((ExceptionHandlerExceptionResolver) exceptionResolver).getReturnValueHandlers();
                if (returnValueHandlerComposite == null) {
                    return;
                }
                SpringMvcPolyfill.addDynamicResponseBodyAdvice(returnValueHandlerComposite.getHandlers(), null, responseBodyAdvice);
            }
        }
    }
}
 
示例9
/**
 * Returns a {@link HandlerExceptionResolverComposite} containing a list of exception
 * resolvers obtained either through {@link #configureHandlerExceptionResolvers} or
 * through {@link #addDefaultHandlerExceptionResolvers}.
 * <p><strong>Note:</strong> This method cannot be made final due to CGLIB constraints.
 * Rather than overriding it, consider overriding {@link #configureHandlerExceptionResolvers}
 * which allows for providing a list of resolvers.
 */
@Bean
public HandlerExceptionResolver handlerExceptionResolver() {
	List<HandlerExceptionResolver> exceptionResolvers = new ArrayList<>();
	configureHandlerExceptionResolvers(exceptionResolvers);
	if (exceptionResolvers.isEmpty()) {
		addDefaultHandlerExceptionResolvers(exceptionResolvers);
	}
	extendHandlerExceptionResolvers(exceptionResolvers);
	HandlerExceptionResolverComposite composite = new HandlerExceptionResolverComposite();
	composite.setOrder(0);
	composite.setExceptionResolvers(exceptionResolvers);
	return composite;
}
 
示例10
@Test
public void exceptionResolvers() throws Exception {
	List<HandlerExceptionResolver> resolvers = ((HandlerExceptionResolverComposite)
			this.config.handlerExceptionResolver()).getExceptionResolvers();

	assertEquals(2, resolvers.size());
	assertEquals(ResponseStatusExceptionResolver.class, resolvers.get(0).getClass());
	assertEquals(SimpleMappingExceptionResolver.class, resolvers.get(1).getClass());
}
 
示例11
@Test
@SuppressWarnings("unchecked")
public void handlerExceptionResolver() throws Exception {
	ApplicationContext context = initContext(WebConfig.class);
	HandlerExceptionResolverComposite compositeResolver =
			context.getBean("handlerExceptionResolver", HandlerExceptionResolverComposite.class);

	assertEquals(0, compositeResolver.getOrder());
	List<HandlerExceptionResolver> expectedResolvers = compositeResolver.getExceptionResolvers();

	assertEquals(ExceptionHandlerExceptionResolver.class, expectedResolvers.get(0).getClass());
	assertEquals(ResponseStatusExceptionResolver.class, expectedResolvers.get(1).getClass());
	assertEquals(DefaultHandlerExceptionResolver.class, expectedResolvers.get(2).getClass());

	ExceptionHandlerExceptionResolver eher = (ExceptionHandlerExceptionResolver) expectedResolvers.get(0);
	assertNotNull(eher.getApplicationContext());

	DirectFieldAccessor fieldAccessor = new DirectFieldAccessor(eher);
	List<Object> interceptors = (List<Object>) fieldAccessor.getPropertyValue("responseBodyAdvice");
	assertEquals(1, interceptors.size());
	assertEquals(JsonViewResponseBodyAdvice.class, interceptors.get(0).getClass());

	LocaleContextHolder.setLocale(Locale.ENGLISH);
	try {
		ResponseStatusExceptionResolver rser = (ResponseStatusExceptionResolver) expectedResolvers.get(1);
		MockHttpServletRequest request = new MockHttpServletRequest("GET", "/");
		MockHttpServletResponse response = new MockHttpServletResponse();
		rser.resolveException(request, response, context.getBean(TestController.class), new UserAlreadyExistsException());
		assertEquals("User already exists!", response.getErrorMessage());
	}
	finally {
		LocaleContextHolder.resetLocaleContext();
	}
}
 
示例12
@Test
public void configureExceptionResolvers() throws Exception {
	List<WebMvcConfigurer> configurers = new ArrayList<>();
	configurers.add(new WebMvcConfigurer() {
		@Override
		public void configureHandlerExceptionResolvers(List<HandlerExceptionResolver> exceptionResolvers) {
			exceptionResolvers.add(new DefaultHandlerExceptionResolver());
		}
	});
	delegatingConfig.setConfigurers(configurers);

	HandlerExceptionResolverComposite composite =
			(HandlerExceptionResolverComposite) delegatingConfig.handlerExceptionResolver();
	assertEquals("Only one custom converter is expected", 1, composite.getExceptionResolvers().size());
}
 
示例13
/**
 * Returns a {@link HandlerExceptionResolverComposite} containing a list
 * of exception resolvers obtained either through
 * {@link #configureHandlerExceptionResolvers(List)} or through
 * {@link #addDefaultHandlerExceptionResolvers(List)}.
 * <p><strong>Note:</strong> This method cannot be made final due to CGLib
 * constraints. Rather than overriding it, consider overriding
 * {@link #configureHandlerExceptionResolvers(List)}, which allows
 * providing a list of resolvers.
 */
@Bean
public HandlerExceptionResolver handlerExceptionResolver() {
	List<HandlerExceptionResolver> exceptionResolvers = new ArrayList<HandlerExceptionResolver>();
	configureHandlerExceptionResolvers(exceptionResolvers);
	if (exceptionResolvers.isEmpty()) {
		addDefaultHandlerExceptionResolvers(exceptionResolvers);
	}
	extendHandlerExceptionResolvers(exceptionResolvers);
	HandlerExceptionResolverComposite composite = new HandlerExceptionResolverComposite();
	composite.setOrder(0);
	composite.setExceptionResolvers(exceptionResolvers);
	return composite;
}
 
示例14
/**
 * Returns a {@link HandlerExceptionResolverComposite} containing a list
 * of exception resolvers obtained either through
 * {@link #configureHandlerExceptionResolvers(List)} or through
 * {@link #addDefaultHandlerExceptionResolvers(List)}.
 * <p><strong>Note:</strong> This method cannot be made final due to CGLib
 * constraints. Rather than overriding it, consider overriding
 * {@link #configureHandlerExceptionResolvers(List)}, which allows
 * providing a list of resolvers.
 */
@Bean
public HandlerExceptionResolver handlerExceptionResolver() {
	List<HandlerExceptionResolver> exceptionResolvers = new ArrayList<HandlerExceptionResolver>();
	configureHandlerExceptionResolvers(exceptionResolvers);

	if (exceptionResolvers.isEmpty()) {
		addDefaultHandlerExceptionResolvers(exceptionResolvers);
	}

	HandlerExceptionResolverComposite composite = new HandlerExceptionResolverComposite();
	composite.setOrder(0);
	composite.setExceptionResolvers(exceptionResolvers);
	return composite;
}
 
示例15
@Test
@SuppressWarnings("unchecked")
public void handlerExceptionResolver() throws Exception {
	ApplicationContext context = initContext(WebConfig.class);
	HandlerExceptionResolverComposite compositeResolver =
			context.getBean("handlerExceptionResolver", HandlerExceptionResolverComposite.class);

	assertEquals(0, compositeResolver.getOrder());
	List<HandlerExceptionResolver> expectedResolvers = compositeResolver.getExceptionResolvers();

	assertEquals(ExceptionHandlerExceptionResolver.class, expectedResolvers.get(0).getClass());
	assertEquals(ResponseStatusExceptionResolver.class, expectedResolvers.get(1).getClass());
	assertEquals(DefaultHandlerExceptionResolver.class, expectedResolvers.get(2).getClass());

	ExceptionHandlerExceptionResolver eher = (ExceptionHandlerExceptionResolver) expectedResolvers.get(0);
	assertNotNull(eher.getApplicationContext());

	DirectFieldAccessor fieldAccessor = new DirectFieldAccessor(eher);
	List<Object> interceptors = (List<Object>) fieldAccessor.getPropertyValue("responseBodyAdvice");
	assertEquals(1, interceptors.size());
	assertEquals(JsonViewResponseBodyAdvice.class, interceptors.get(0).getClass());

	LocaleContextHolder.setLocale(Locale.ENGLISH);
	try {
		ResponseStatusExceptionResolver rser = (ResponseStatusExceptionResolver) expectedResolvers.get(1);
		MockHttpServletRequest request = new MockHttpServletRequest("GET", "/");
		MockHttpServletResponse response = new MockHttpServletResponse();
		rser.resolveException(request, response, context.getBean(TestController.class), new UserAlreadyExistsException());
		assertEquals("User already exists!", response.getErrorMessage());
	}
	finally {
		LocaleContextHolder.resetLocaleContext();
	}
}
 
示例16
@Test
public void configureExceptionResolvers() throws Exception {
	List<WebMvcConfigurer> configurers = new ArrayList<WebMvcConfigurer>();
	configurers.add(new WebMvcConfigurerAdapter() {
		@Override
		public void configureHandlerExceptionResolvers(List<HandlerExceptionResolver> exceptionResolvers) {
			exceptionResolvers.add(new DefaultHandlerExceptionResolver());
		}
	});
	delegatingConfig.setConfigurers(configurers);

	HandlerExceptionResolverComposite composite =
		(HandlerExceptionResolverComposite) delegatingConfig.handlerExceptionResolver();
	assertEquals("Only one custom converter is expected", 1, composite.getExceptionResolvers().size());
}
 
示例17
@Test
public void exceptionResolvers() throws Exception {
	HandlerExceptionResolver exceptionResolver = this.config.handlerExceptionResolver();
	assertEquals(1, ((HandlerExceptionResolverComposite) exceptionResolver).getExceptionResolvers().size());
}