简体   繁体   English

如何使用@ControllerAdvice 和@ExceptionHandler 处理404 异常?

[英]How to handle 404 exceptions using @ControllerAdvice and @ExceptionHandler?

I have a problem with Spring's exception handling for controllers.我对 Spring 的控制器异常处理有疑问。 I have a class annotated with @RestControllerAdvice with a couple of @ExceptionHandler 's, like this:我有一个 class 用@RestControllerAdvice和几个@ExceptionHandler注释,像这样:

@ExceptionHandler(HttpRequestMethodNotSupportedException::class)
fun methodNotSupportedException(
    exception: HttpRequestMethodNotSupportedException,
    request: HttpServletRequest
): ResponseEntity<ApiError> {
    logger().error("Method not supported: {}", exception.message)
    val methodNotAllowed = HttpStatus.METHOD_NOT_ALLOWED
    val apiError = logAndBuildApiError(request, methodNotAllowed, exception)
    return ResponseEntity(apiError, methodNotAllowed)
}

and they work perfectly fine.他们工作得很好。 In this case, when I'm trying to use an non-implemented HTTP method like POST:在这种情况下,当我尝试使用像 POST 这样的未实现的 HTTP 方法时:

{
    "requestUri": "/api/v1/items",
    "status": 405,
    "statusText": "Method Not Allowed",
    "createdAt": "2023-01-12T16:50:36.55422+02:00",
    "errorMessage": "Request method 'POST' not supported"
}

What I would like to achieve is to handle situations when someone is trying to reach an non-existing endpoint, ie the correct one is GET http://localhost:8080/api/v1/items .我想要实现的是处理有人试图到达不存在的端点的情况,即正确的端点是GET http://localhost:8080/api/v1/items

But when I'm trying to reach http://localhost:8080/api/v1/itemss , which is of course nonexistent, I recieve a regular Spring whitelabel error page, but I would like to receive a JSON like in the former example:但是当我试图到达http://localhost:8080/api/v1/itemss时,这当然是不存在的,我收到一个常规的 Spring 白标签错误页面,但我想收到一个 JSON 就像前面的例子:

{
    "requestUri": "/api/v1/itemss",
    "status": 404,
    "statusText": "Not Found",
    "createdAt": "2023-01-12T16:52:06.932108+02:00",
    "errorMessage": "Some error message"
}

How do I implement a @ExceptionHandler so it could handle exceptions related to non-existing resources?我如何实现@ExceptionHandler以便它可以处理与不存在的资源相关的异常?

spring.mvc.throw-exception-if-no-handler-found works in conjunction with spring.mvc.static-path-pattern . spring.mvc.throw-exception-if-no-handler-foundspring.mvc.static-path-pattern结合使用。 By default, the static path pattern is /**, which includes the whitelabel error pages that you're seeing.默认情况下,static 路径模式是 /**,其中包括您看到的白标签错误页面。

See https://github.com/spring-projects/spring-boot/pull/31660 and https://gitter.im/spring-projects/spring-boot?at=62ba1378568c2c30d30790af and https://docs.spring.io/spring-boot/docs/current/reference/htmlsingle/#web.servlet.spring-mvc.static-content请参阅https://github.com/spring-projects/spring-boot/pull/31660https://gitter.im/spring-projects/spring-boot?at=62ba1378568c2c30d30790afhttps://docs.881799283.io5690af /spring-boot/docs/current/reference/htmlsingle/#web.servlet.spring-mvc.static-content

Option one is to set these two properties in your configuration.选项一是在您的配置中设置这两个属性。

spring:
  mvc:
    throw-exception-if-no-handler-found: true
    static-path-pattern: /static

Option 2 is to add @EnableWebMvc to your spring boot application, and set the spring.mvc.throw-exception-if-no-handler-found property to true.选项 2 是将@EnableWebMvc添加到您的 spring 引导应用程序,并将spring.mvc.throw-exception-if-no-handler-found属性设置为 true。 By adding EnableWebMvc you'll be getting the WebMvcConfigurationSupport bean, which will cause Spring not to initialize the WebMvcAutoConfiguration and thereby not set the static-path-pattern.通过添加EnableWebMvc ,您将获得WebMvcConfigurationSupport bean,这将导致 Spring 不初始化WebMvcAutoConfiguration ,从而不设置静态路径模式。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 如何在ControllerAdvice中使用ExceptionHandler处理控制器中ExceptionHandler抛出的异常? - How to handle exception thrown from ExceptionHandler in controller with ExceptionHandler in ControllerAdvice? 使用 @ExceptionHandler 处理自定义异常 - Handle custom exceptions using @ExceptionHandler @ControllerAdvice 和 @ExceptionHandler 不捕获异常 - @ControllerAdvice with @ExceptionHandler don't catch exceptions @ControllerAdvice 不处理异常 - @ControllerAdvice doesn't handle exceptions Spring启动:使用ControllerAdvice for REST处理自定义异常 - Spring boot: Handle Custom Exceptions using ControllerAdvice for REST 如何使用ControllerAdvice注释的类来处理不同类型的异常? - How to have a class annotated by ControllerAdvice to handle different types of exceptions? @ControllerAdvice优于@ExceptionHandler或HandlerExceptionResolver处理异常的优点是什么? - What are the advantages of @ControllerAdvice over @ExceptionHandler or HandlerExceptionResolver for handling exceptions? 如何处理Ajax,Spring MVC 3.2,@ ControllerAdvice调用的404异常 - How to handle 404 exception invoked by ajax, Spring MVC 3.2, @ControllerAdvice 如何通过@ControllerAdvice中的@ResponseStatus捕获异常 - How to catch exceptions by @ResponseStatus in @ControllerAdvice @ExceptionHandler不处理抛出的异常 - @ExceptionHandler doesn't handle the thrown exceptions
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM