Skip to content
🔴🟠🟡🟢🔵🟣🟤⚫⚪

(二十九)自定义全局拦截404异常

基础项目地址:

https://gitee.com/springzb/admin-boot

新增以下配置:

java
spring:  
  # 因为Springfox 使用的路径匹配是基于AntPathMatcher的,而Spring Boot 2.6.X使用的是PathPatternMatcher
  mvc:
    # 允许mvc抛出404异常
    throw-exception-if-no-handler-found: true
  # 关闭spring自带的映射,会导致swagger也不能访问,需指定swagger的静态资源处理
  web:
    resources:
      add-mappings: false

全局拦截404异常

java
@Slf4j
@RestControllerAdvice
public class GlobalExceptionHandler {


    /**
     * 捕获 404 异常
     * @param exception
     * @return
     */
    @ExceptionHandler({NoHandlerFoundException.class, HttpRequestMethodNotSupportedException.class})
    @ResponseStatus(HttpStatus.NOT_FOUND)
    public R handle(Exception exception) {
        String message = exception.getMessage();
        log.error("404捕获错误信息: {}", message);
        return R.fail("找不到对应资源");
    }

}

配置了禁用模板后swagger会失效:

java
package cn.mesmile.admin.common.config.swagger;

import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;

/**
 * @author zb
 * @Description
 *     # 关闭spring自带的映射,会导致swagger也不能访问,需指定swagger的静态资源处理
 *     spring.web.resources.add-mappings: false  会导致swagger也不能访问
 */
@Configuration
public class SwaggerResourceMvcConfig implements WebMvcConfigurer {

    /**
     * 需指定swagger的静态资源处理
     */
    @Override
    public void addResourceHandlers(ResourceHandlerRegistry registry) {
        // 这里加上任意路径后会去匹配上,/error 资源,返回默认的404页面,所以这里先注释
//        registry.addResourceHandler("/**").addResourceLocations("classpath:/static/");

        /** 配置knife4j 显示文档 */
        registry.addResourceHandler("doc.html")
                .addResourceLocations("classpath:/META-INF/resources/");
        /**
         * 配置swagger-ui显示文档
         */
        registry.addResourceHandler("swagger-ui.html")
                .addResourceLocations("classpath:/META-INF/resources/");
        /** 公共部分内容 */
        registry.addResourceHandler("/webjars/**")
                .addResourceLocations("classpath:/META-INF/resources/webjars/");
    }


}