我对Spring的控制器异常处理有一个问题。我有一个用@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-found
与spring.mvc.static-path-pattern
。默认情况下,静态路径模式是/**,其中包括您正在看到的白标签错误页面。
见https://github.com/spring-projects/spring-boot/pull/31660和https://gitter.im/spring-projects/spring-boot?at=62ba1378568c2c30d30790af和https://docs.spring.io/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
,从而不设置static-path-pattern。