Spring GlobalExceptionHandler : java.lang.IllegalStateException: 无法解析参数 [0] ... 没有合适的解析器

pyb*_*pyb 5 spring

尝试设置全局异常处理程序以响应通用错误响应时出现以下错误:

@RestControllerAdvice
class GlobalExceptionHandler {

    @ExceptionHandler(HttpClientErrorException::class)
    @ResponseStatus(HttpStatus.BAD_REQUEST)
    fun handleClientException(exception: HttpClientErrorException): ErrorDto {
        // do something with client errors, like logging
        return ErrorDto(errorMessage)
    }

    @ExceptionHandler(Exception::class)
    @ResponseStatus(HttpStatus.INTERNAL_SERVER_ERROR)
    fun handleServerException(exception: HttpClientErrorException): ErrorDto {
        // do some other thing with server errors, like alerts
        return ErrorDto(errorMessage)
    }

}

data class ErrorDto(val message: String)

@RestController
class DemoController {
    @GetMapping("/error")
    @ResponseBody
    fun error(): ErrorDto {
        throw RuntimeException("test")
    }
}
Run Code Online (Sandbox Code Playgroud)

和错误:

ExceptionHandlerExceptionResolver : Failure in @ExceptionHandler
public ErrorDto
GlobalExceptionHandler.handleServerException(org.springframework.web.client.HttpClientErrorException)

java.lang.IllegalStateException: Could not resolve parameter [0] in
public ErrorDto
GlobalExceptionHandler.handleServerException(org.springframework.web.client.HttpClientErrorException):
No suitable resolver    at
org.springframework.web.method.support.InvocableHandlerMethod.getMethodArgumentValues(InvocableHandlerMethod.java:163)
    at
org.springframework.web.method.support.InvocableHandlerMethod.invokeForRequest(InvocableHandlerMethod.java:134)
    at
org.springframework.web.servlet.mvc.method.annotation.ServletInvocableHandlerMethod.invokeAndHandle(ServletInvocableHandlerMethod.java:102)
    at
(...)
java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:624)
    at java.lang.Thread.run(Thread.java:748)
Run Code Online (Sandbox Code Playgroud)

这不是spring mvc 控制器错误 java.lang.IllegalStateException: 参数 [0] 没有合适的解析器的副本,这是一个休眠问题。我没有在这里使用 Hibernate。

pyb*_*pyb 8

就我而言,这是一个复制粘贴错误。

我抛出了一个,RuntimeException但我配置了异常处理程序以支持HttpClientErrorException:

fun handleServerException(exception: HttpClientErrorException)

在这种情况下,修复方法是在@ExceptionHandler注释中使用与方法参数中相同的 Exception 类:

@ExceptionHandler(Exception::class) // <-- must match method parameter
@ResponseStatus(HttpStatus.INTERNAL_SERVER_ERROR)
fun handleServerException(exception: Exception): ErrorDto { // <-- fix here
    // do some other thing with server errors, like alerts
    return ErrorDto(errorMessage)
}
Run Code Online (Sandbox Code Playgroud)

  • 这也发生在我身上,还要确保导入正确的“ServerHttpRequest”类。就我而言,我导入了“org.springframework.http.server.ServerHttpRequest”,而它应该是“org.springframework.http.server.reactive.ServerHttpRequest”。请注意,它位于 **reactive** 包中。这与您使用“spring-boot-starter-web”或“spring-boot-starter-webflux”的项目有关 (2认同)