问题描述
我想覆盖404错误的html错误页面作为JSON响应.当我在没有 @EnableWebMvc
的情况下使用 @ControllerAdvice
时,它将无法正常工作.
I want to override html error page for 404 responses as an JSON response. When i use @ControllerAdvice
without @EnableWebMvc
it is not working.
@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);
}
}
有没有 @EnableWebMvc
的自定义异常处理选项,因为它会覆盖在application.yml中声明的Spring配置.
Is there an option for custom exception handling without @EnableWebMvc
, because it overrides Spring configurations which are declared inside application.yml.
推荐答案
我通过在application.yml中添加配置之一轻松解决了问题.
I easily resolved problem by adding one of configurations in application.yml.
spring.mvc.throw-exception-if-no-handler-found=true
spring.resources.add-mappings=false
或
spring.mvc.throw-exception-if-no-handler-found=true
spring.mvc.static-path-pattern: /static
如果您不限制Spring并且没有处理程序与您的请求匹配,则spring会尝试查找静态内容.
If you don't restrict Spring and no handler matches with your request, then spring tries to look for static content.
这篇关于没有@ EnableWebMvc,NoHandlerFoundException的自定义异常处理程序将无法工作的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!