Knife4j文档的会被全局异常处理器拦截的问题解决
一、发现问题
在SpringBoot 3.4.5中,还有knife4j-openapi3的版本中,doc.html会被拦截器拦截
问题背景
介绍Knife4j文档的基本功能及其在API文档生成中的重要性。阐述全局异常处理器的概念及其在Spring Boot项目中的作用。提出Knife4j文档在某些情况下会被全局异常处理器拦截的问题。
问题分析
分析Knife4j文档被全局异常处理器拦截的原因。探讨全局异常处理器的配置方式及其对Knife4j文档的影响。讨论常见的异常处理策略及其对API文档生成的影响。
解决方案
提供解决Knife4j文档被全局异常处理器拦截的具体方法。介绍如何通过配置全局异常处理器来排除Knife4j文档的路径。讨论如何通过自定义异常处理逻辑来避免对Knife4j文档的干扰。
二、代码示例
1、在全局异常处理器加上@Hidden
/*** 全局异常处理器*/
@RestControllerAdvice
@Hidden
public class GlobalExceptionHandler {@ExceptionHandler(BusinessException.class)public BaseResponse<?> businessExceptionHandler(BusinessException e) {
// log.error("BusinessException", e);return Result.error(e.getCode(), e.getMessage());}@ExceptionHandler(RuntimeException.class)public BaseResponse<?> runtimeExceptionHandler(RuntimeException e) {
// log.error("RuntimeException", e);return Result.error(ErrorCode.SYSTEM_ERROR, "系统错误");}}
2、WebMVCConfig中设置拦截的路径,还有加上加上静态访问资源
@Configuration
@RequiredArgsConstructor
public class WebMvcConfig implements WebMvcConfigurer {private final AuthenticationInterceptor authenticationInterceptor;@Overridepublic void addInterceptors(InterceptorRegistry registry) {registry.addInterceptor(this.authenticationInterceptor).excludePathPatterns(// Knife4j 文档相关"/doc.html/**", // 文档页面"/webjars/**", // 静态资源"/swagger-resources/**", // Swagger 资源"/v3/api-docs/**", // OpenAPI 规范端点"/favicon.ico" // 网站图标).excludePathPatterns("/user/register/**","/user/login/**");}@Overridepublic void addResourceHandlers(ResourceHandlerRegistry registry) {//配置拦截器访问静态资源registry.addResourceHandler("doc.html").addResourceLocations("classpath:/META-INF/resources/");registry.addResourceHandler("/favicon.ico").addResourceLocations("classpath:/META-INF/resources/");registry.addResourceHandler("/webjars/**").addResourceLocations("classpath:/META-INF/resources/webjars/");}}