我有一个GlobalExceptionHandler来捕获所有抛出的异常并返回正确的返回码。一切正常,除非发生OptimisticLockingFailureException,并且我不知道为什么会这样。
GlobalExceptionHandler:
@Component
@Order(-2)
class GlobalExceptionHandler : WebExceptionHandler {
override fun handle(exchange: ServerWebExchange, throwable: Throwable): Mono<Void> = handleException(throwable)
.flatMap { it.writeTo(exchange, HandlerStrategiesResponseContext(HandlerStrategies.withDefaults())) }
.flatMap { Mono.empty<Void>() }
private fun handleException(ex: Throwable): Mono<ServerResponse> = when (ex) {
is EntityNotFoundException -> notFound(ex.message)
is InvalidRequestException,
is ReferenceKeyNotKnown,
is InvalidContractTypeException -> badRequest(ex.message)
is DuplicateKeyException,
is TransactionException,
is OptimisticLockingFailureException -> conflict(ex.message)
else -> errorResponse(HttpStatus.INTERNAL_SERVER_ERROR, ex.message)
}
private class HandlerStrategiesResponseContext(val strategies: HandlerStrategies) : ServerResponse.Context {
override fun viewResolvers(): MutableList<ViewResolver> = strategies.viewResolvers()
override fun messageWriters(): MutableList<HttpMessageWriter<*>> = strategies.messageWriters()
}
}
notFound,badRequest和errorResponse函数返回具有正确状态码和消息的Mono。
任何可以帮助我并指出正确方向的人,为什么OptimistickLockingException不会触发此错误?
Thx!
所以未触发异常处理程序的原因是,我们的处理程序中仍然有一个.onErrorContinue步骤,该步骤记录了异常,而没有其他任何记录。将日志记录移到GlobalExceptionHandler并除去onErrorContinue之后,GlobalExceptionHandler可以按预期工作]