NoHandlerFoundException 的自定义异常处理程序在没有 @EnableWebMvc 的情况下不起作用

utk*_*mez 9 java spring-boot

我想将 404 响应的 html 错误页面覆盖为 JSON 响应。当我@ControllerAdvice不使用@EnableWebMvc它时,它不起作用。

@EnableWebMvc   // if i remove this, it is not working
@ControllerAdvice
@Order(Ordered.HIGHEST_PRECEDENCE)
public class GlobalControllerExceptionHandler {

    @ExceptionHandler(NoHandlerFoundException.class)
    public ResponseEntity<ZeusErrorDTO> noHandlerFoundException(
                    HttpServletRequest request, 
                    NoHandlerFoundException exception) {

        ErrorDTO errorDTO = new ErrorDTO();
        return new ResponseEntity<>(errorDTO, HttpStatus.NOT_FOUND);
    }
} 
Run Code Online (Sandbox Code Playgroud)

是否有自定义异常处理的选项@EnableWebMvc,因为它会覆盖在 application.yml 中声明的 Spring 配置。

utk*_*mez 9

我通过在 application.yml 中添加配置之一轻松解决了问题。

spring.mvc.throw-exception-if-no-handler-found=true
spring.resources.add-mappings=false
Run Code Online (Sandbox Code Playgroud)

或者

spring.mvc.throw-exception-if-no-handler-found=true
spring.mvc.static-path-pattern: /static
Run Code Online (Sandbox Code Playgroud)

如果您不限制 Spring 并且没有处理程序与您的请求匹配,那么 spring 会尝试查找静态内容。


Emd*_*won 9

通常@utkusonmez 答案工作正常,但在我的情况下不是,因为我使用的是招摇。所以我所做的就是在我的application.properties文件中添加以下属性

spring.mvc.throw-exception-if-no-handler-found=true
spring.mvc.static-path-pattern=/swagger*
Run Code Online (Sandbox Code Playgroud)

现在,这两个NoHandlerFoundExceptionswagger-ui优良工程。

  • 这个答案非常受欢迎。关于此主题的许多其他问题都建议使用“静态位置”或完全启用资源映射,但只有“静态路径模式”允许 Swagger 工作而不影响异常处理。 (2认同)