簡體   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