diff --git a/src/backend/replication/libpqwalreceiver/libpqwalreceiver.c b/src/backend/replication/libpqwalreceiver/libpqwalreceiver.c
index ebe9c91..e3e5f81 100644
--- a/src/backend/replication/libpqwalreceiver/libpqwalreceiver.c
+++ b/src/backend/replication/libpqwalreceiver/libpqwalreceiver.c
@@ -681,12 +681,25 @@ libpqrcv_receive(WalReceiverConn *conn, char **buffer,
 		{
 			PQclear(res);
 
-			/* Verify that there are no more results */
+			/* Verify that there are no more results. */
 			res = PQgetResult(conn->streamConn);
 			if (res != NULL)
+			{
+				PQclear(res);
+
+				/*
+				 * The connection might have been disconnected,  which is
+				 * normal here as this will be reached when the upstream was
+				 * shut down and we handle it in the caller(s).
+				 */
+				if (PQstatus(conn->streamConn) == CONNECTION_BAD)
+					return -1;
+
 				ereport(ERROR,
 						(errmsg("unexpected result after CommandComplete: %s",
 								PQerrorMessage(conn->streamConn))));
+			}
+
 			return -1;
 		}
 		else if (PQresultStatus(res) == PGRES_COPY_IN)
