尝试设置全局异常处理程序以响应一般错误响应时,出现以下错误:
@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 controller error java.lang.IllegalStateException: No suitable resolver for argument [0]的重复,这是一个Hibernate问题。我不是在这里使用Hibernate。
答案 0 :(得分:1)
就我而言,这是一个复制粘贴错误。
我抛出了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)
}