Skip to content

Commit 080a269

Browse files
committed
Set UncaughtExceptionHandler in onQueryStarted to ensure catching fatal errors during query initialization
1 parent 00074b5 commit 080a269

File tree

1 file changed

+16
-6
lines changed

1 file changed

+16
-6
lines changed

sql/core/src/test/scala/org/apache/spark/sql/streaming/StreamTest.scala

Lines changed: 16 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -248,6 +248,21 @@ trait StreamTest extends QueryTest with SharedSQLContext with Timeouts {
248248

249249
@volatile
250250
var streamThreadDeathCause: Throwable = null
251+
// Set UncaughtExceptionHandler in `onQueryStarted` so that we can ensure catching fatal errors
252+
// during query initialization.
253+
val listener = new StreamingQueryListener {
254+
override def onQueryStarted(event: QueryStartedEvent): Unit = {
255+
Thread.currentThread.setUncaughtExceptionHandler(new UncaughtExceptionHandler {
256+
override def uncaughtException(t: Thread, e: Throwable): Unit = {
257+
streamThreadDeathCause = e
258+
}
259+
})
260+
}
261+
262+
override def onQueryProgress(event: QueryProgressEvent): Unit = {}
263+
override def onQueryTerminated(event: QueryTerminatedEvent): Unit = {}
264+
}
265+
sparkSession.streams.addListener(listener)
251266

252267
// If the test doesn't manually start the stream, we do it automatically at the beginning.
253268
val startedManually =
@@ -364,12 +379,6 @@ trait StreamTest extends QueryTest with SharedSQLContext with Timeouts {
364379
triggerClock = triggerClock)
365380
.asInstanceOf[StreamingQueryWrapper]
366381
.streamingQuery
367-
currentStream.microBatchThread.setUncaughtExceptionHandler(
368-
new UncaughtExceptionHandler {
369-
override def uncaughtException(t: Thread, e: Throwable): Unit = {
370-
streamThreadDeathCause = e
371-
}
372-
})
373382
// Wait until the initialization finishes, because some tests need to use `logicalPlan`
374383
// after starting the query.
375384
currentStream.awaitInitialization(streamingTimeout.toMillis)
@@ -545,6 +554,7 @@ trait StreamTest extends QueryTest with SharedSQLContext with Timeouts {
545554
case (key, Some(value)) => sparkSession.conf.set(key, value)
546555
case (key, None) => sparkSession.conf.unset(key)
547556
}
557+
sparkSession.streams.removeListener(listener)
548558
}
549559
}
550560

0 commit comments

Comments
 (0)