use of com.alibaba.csp.sentinel.adapter.spring.webmvc.callback.BlockExceptionHandler in project blade-tool by chillzhuang.
the class BladeSentinelFilterConfiguration method sentinelWebMvcConfig.
@Bean
public SentinelWebMvcConfig sentinelWebMvcConfig(SentinelProperties properties, Optional<UrlCleaner> urlCleanerOptional, Optional<BlockExceptionHandler> blockExceptionHandlerOptional, Optional<RequestOriginParser> requestOriginParserOptional) {
SentinelWebMvcConfig sentinelWebMvcConfig = new SentinelWebMvcConfig();
sentinelWebMvcConfig.setHttpMethodSpecify(properties.getHttpMethodSpecify());
sentinelWebMvcConfig.setWebContextUnify(properties.getWebContextUnify());
if (blockExceptionHandlerOptional.isPresent()) {
blockExceptionHandlerOptional.ifPresent(sentinelWebMvcConfig::setBlockExceptionHandler);
} else {
if (StringUtils.hasText(properties.getBlockPage())) {
sentinelWebMvcConfig.setBlockExceptionHandler(((request, response, e) -> response.sendRedirect(properties.getBlockPage())));
} else {
sentinelWebMvcConfig.setBlockExceptionHandler(new DefaultBlockExceptionHandler());
}
}
urlCleanerOptional.ifPresent(sentinelWebMvcConfig::setUrlCleaner);
requestOriginParserOptional.ifPresent(sentinelWebMvcConfig::setOriginParser);
return sentinelWebMvcConfig;
}
use of com.alibaba.csp.sentinel.adapter.spring.webmvc.callback.BlockExceptionHandler in project Sentinel by alibaba.
the class InterceptorConfig method addSpringMvcInterceptor.
private void addSpringMvcInterceptor(InterceptorRegistry registry) {
// Config
SentinelWebMvcConfig config = new SentinelWebMvcConfig();
config.setBlockExceptionHandler(new BlockExceptionHandler() {
@Override
public void handle(HttpServletRequest request, HttpServletResponse response, BlockException e) throws Exception {
String resourceName = e.getRule().getResource();
// Depending on your situation, you can choose to process or throw
if ("/hello".equals(resourceName)) {
// Do something ......
// Write string or json string;
response.getWriter().write("/Blocked by sentinel");
} else {
// Handle in global exception handling
throw e;
}
}
});
// Custom configuration if necessary
config.setHttpMethodSpecify(false);
config.setWebContextUnify(true);
config.setOriginParser(new RequestOriginParser() {
@Override
public String parseOrigin(HttpServletRequest request) {
return request.getHeader("S-user");
}
});
// Add sentinel interceptor
registry.addInterceptor(new SentinelWebInterceptor(config)).addPathPatterns("/**");
}
Aggregations