Skip to content

Add coroutine variant of WebExceptionHandler #32931

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
@@ -0,0 +1,15 @@
package org.springframework.web.server

import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.reactor.mono
import reactor.core.publisher.Mono
import kotlin.coroutines.CoroutineContext

abstract class CoWebExceptionHandler : WebExceptionHandler {
final override fun handle(exchange: ServerWebExchange, ex: Throwable): Mono<Void> {
val context = exchange.attributes[CoWebFilter.COROUTINE_CONTEXT_ATTRIBUTE] as CoroutineContext?
return mono(context ?: Dispatchers.Unconfined) { coHandle(exchange, ex) }.then()
}

protected abstract suspend fun coHandle(exchange: ServerWebExchange, ex: Throwable)
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,28 @@
package org.springframework.web.server

import org.assertj.core.api.Assertions.assertThat
import org.junit.jupiter.api.Test
import org.springframework.web.testfixture.http.server.reactive.MockServerHttpRequest
import org.springframework.web.testfixture.server.MockServerWebExchange
import reactor.test.StepVerifier

class CoWebExceptionHandlerTest {
@Test
fun handle() {
val exchange = MockServerWebExchange.from(MockServerHttpRequest.get("https://example.com"))
val ex = RuntimeException()

val handler = MyCoWebExceptionHandler()
val result = handler.handle(exchange, ex)

StepVerifier.create(result).verifyComplete()

assertThat(exchange.attributes["foo"]).isEqualTo("bar")
}
}

private class MyCoWebExceptionHandler : CoWebExceptionHandler() {
override suspend fun coHandle(exchange: ServerWebExchange, ex: Throwable) {
exchange.attributes["foo"] = "bar"
}
}