我有一个全局错误处理程序类来捕获自定义异常并返回自定义响应。
当尝试使用@Override
或@ExceptionHandler
捕获标准异常时,Spring Boot仍会返回其自定义响应对象。即使我可以看到@ExceptionHandler
方法捕获了异常。
我不确定它是否与webflux应用程序有关。
这是我的代码:
@RestController
@RequestMapping("/c")
class CaseController(private val caseManagementService:
CaseManagementService) {
@PostMapping()
fun createCase(@Valid @RequestBody caseRequest: CaseRequestDto,
@RequestHeader(value = "X-API-KEY") xApiKey: String):
ResponseEntity<CaseResponseDto> {
if (StringUtils.isBlank(xApiKey)) {
throw CaseManagementIllegalArgumentException("Invalid
request")
}
return caseManagementService.createAccount(caseRequest)
}
}
全局处理程序:
@ControllerAdvice
class ControllerExceptionHandler {
@ExceptionHandler(RuntimeException::class)
fun handleRunTimeException(e: RuntimeException): ResponseEntity<Any>
{
logger.error("Exception caught in handleRunTimeException: $e", e.printStackTrace())
val response = ErrorResponse(MessageConstants.SYSTEM_ERROR, e.message, e, serverError)
return ResponseEntity<Any>(response, badRequest)
}
}
此方法应该返回我的ErrorResponse
对象,但是spring boot仍然返回其标准响应,如下所示:
"timestamp": "2020-10-28T01:02:13.264+00:00",
"path": "/svoc/case-management/v1/cases",
"status": 500,
"error": "Internal Server Error",
"message": "JSON encoding error:",
"requestId": "d599572b-2",
"trace":"...."
任何想法都会感激它。