spring - 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。
解决方案
就我而言,这是一个复制粘贴错误。
我正在抛出一个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)
}
推荐阅读
- javascript - Div Slider 和 Display:Table-Cell 的 JS/CSS 问题
- apache-kafka-streams - Kafka Streams:如何使用 persistentKeyValueStore 从磁盘重新加载现有消息?
- jakarta-ee - MDB 未收到来自消费者的消息
- php - 如何在上一篇文章缩略图中修复“尝试获取非对象的属性”通知
- qt - 如何在 qtwebbrowser 应用程序中添加 tslib 插件?
- c# - Unity runner 游戏的滑动控件
- java - Solr 8.1 启动错误 - maxBooleanClauses
- android - 如何防止用户关闭 GPS、Wifi 和蓝牙?
- python-3.x - 如何对结果基于while循环中包含的条件语句的函数进行单元测试
- html - 如何间隔两个按钮