我想将 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 配置。
我通过在 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 会尝试查找静态内容。
通常@utkusonmez 答案工作正常,但在我的情况下不是,因为我使用的是招摇。所以我所做的就是在我的application.properties文件中添加以下属性
spring.mvc.throw-exception-if-no-handler-found=true
spring.mvc.static-path-pattern=/swagger*
Run Code Online (Sandbox Code Playgroud)
现在,这两个NoHandlerFoundException和swagger-ui优良工程。
| 归档时间: |
|
| 查看次数: |
4068 次 |
| 最近记录: |