抱歉,我真的不能分享整个代码,但我会尽力解释这个问题。
我尝试使用以下代码在Controller Advice中捕获NoHandlerFoundException:
控制器建议代码段
@ExceptionHandler({NoHandlerFoundException.class})
public ResponseEntity<ErrorResponse> requestHandlerNotFound(NoHandlerFoundException e, HttpServletRequest request, HttpServletResponse response) {
return new ResponseEntity(new ErrorResponse(e.getMessage(), SomeConstant, SomeConstant), HttpStatus.BAD_REQUEST)
}
注意:我已经在这个类中添加了@Order(Ordered.HIGHEST_PRECEDENCE)。
application.properties具有以下属性:
spring.mvc.throw-exception-if-no-handler-found=true
spring.web.resources.add-mappings=true
现在来谈谈这个问题:
当我创建一个GETMapping时,我得到了所需的响应,如:@GetMapping("/loan/{pathvariable}/somethings")
并尝试命中--http://localhost:8080/loan/123 A/something(“s”是从somethings结束失踪)然后我得到所需的错误
但当我从贷款变成贷款时@GetMapping("/loans/{pathvariable}/somethings")
-- and try to hit --http://localhost:8080/loans/123A/something(“s”is missing in the end from somethings)then this is not caught by NohandlerFoundException.
我得到的是:
15:26:58.065 [http-nio-8080-exec-6] DEBUG o.s.web.servlet.DispatcherServlet - GET“/贷款/123/something”,parameters={}
15:26:58.066 [http-nio-8080-exec-6] DEBUG o.s.d.r.w.RepositoryRestHandlerMapping - Mapped to org.springframework.data.rest.webmvc.RepositoryPropertyReferenceController#followPropertyReference(RootResourceInformation,Serializable,String,PersistentEntityResourceAssembler)
15:26:58.067 [http-nio-8080-exec-6] DEBUG o.s.o.j.s.OpenEntityManagerInViewInterceptor -OpenEntityManagerInViewInterceptor中打开JPA EntityManager
15:26:58.086 [http-nio-8080-exec-6] DEBUG o.s.w.s.m.m.a.ExceptionHandlerExceptionResolver - Using @ExceptionHandler org.springframework.data.rest.webmvc.RepositoryRestExceptionHandler#handleNotFound(ResourceNotFoundException)
15:26:58.096 [http-nio-8080-exec-6]调试o.s.w.s.m.m.a.HttpEntityMethodProcessor -使用'application/octet-stream',给定[/]和支持[/]
15:26:58.098 [http-nio-8080-exec-6] DEBUG o.s.w.s.m.a. ExceptionHandlerResolver- Resolved [org.springframework.data.rest.webmvc.ResourceNotFoundException:找不到EntityRepresentationModel]
15:26:58.098 [http-nio-8080-exec-6] DEBUG o.s.o.j.s.OpenEntityManagerInViewInterceptor -在OpenEntityManagerInViewInterceptor中关闭JPA EntityManager
15:26:58.098 [http-nio-8080-exec-6] DEBUG o.s.web.servlet.DispatcherServlet -已完成404 NOT_FOUND
SpringBoot版本:3.0.0
请救救我!
1条答案
按热度按时间dgtucam11#
这不是真正的根本原因,但我能够变通并捕获未被NoHandlerFoundException捕获的URL,而是引发ResourceNotFoundException
使用此方法,我仍然能够捕获类似的NoHandlerFoundException输出。