繁体   English   中英

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

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

我对 Spring 的控制器异常处理有疑问。 我有一个 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)
}

他们工作得很好。 在这种情况下,当我尝试使用像 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"
}

我想要实现的是处理有人试图到达不存在的端点的情况,即正确的端点是GET http://localhost:8080/api/v1/items

但是当我试图到达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"
}

我如何实现@ExceptionHandler以便它可以处理与不存在的资源相关的异常?

spring.mvc.throw-exception-if-no-handler-foundspring.mvc.static-path-pattern结合使用。 默认情况下,static 路径模式是 /**,其中包括您看到的白标签错误页面。

请参阅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

选项一是在您的配置中设置这两个属性。

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

选项 2 是将@EnableWebMvc添加到您的 spring 引导应用程序,并将spring.mvc.throw-exception-if-no-handler-found属性设置为 true。 通过添加EnableWebMvc ,您将获得WebMvcConfigurationSupport bean,这将导致 Spring 不初始化WebMvcAutoConfiguration ,从而不设置静态路径模式。

暂无
暂无

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

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM