首页 > 解决方案 > Spring GlobalExceptionHandler:java.lang.IllegalStateException:无法解析参数[0] ...没有合适的解析器

问题描述

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

@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")
    }
}

和错误:

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)

这不是spring mvc 控制器错误 java.lang.IllegalStateException: No proper resolver for argument [0]的重复,这是一个 Hibernate 问题。我在这里没有使用 Hibernate。

标签: spring

解决方案


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

我正在抛出一个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)
}

推荐阅读