Throw an error if channel is empty

I have a list of prefixes and a list of files:
valid_prefixes = list: [prefixes…]
files_ch = tuple: [prefix, [files]…]
I then want to join the two, and only the files with the valid prefixes remain:
filtered_files_ch = tuple: [prefix, [files]…]

I want to add the important error checking, where if none of the files match the valid prefixes, I want to throw an error. i.e. if the filtered_files_ch is empty, throw and error and quit the pipeline.

How can I approach this? I understand that nextflow doesn’t know whether something will be empty at compile time.

Hello @Ashton_Teng

Welcome to the community forum :slight_smile:

See the snippet below for quitting a pipeline if a channel is empty.

Channel
  .empty()
  .ifEmpty { error("The channel was empty. Quitting...") }
  .set { my_ch }

If it weren’t empty, it would be stored in the variable my_ch. The output should look like:

Let’s think of a slightly more complex example. I have a channel that isn’t empty, but to some extent, I want to consider it empty. Let’s say there’s something missing that is important. See the example below:

Channel
  .of(['Name': 'Marcel'], ['Name': 'Ashton'])
  .filter { it.Name == 'Bob' }
  .ifEmpty { error("There is no name Bob in the channel") }
  .view { it['Name'] }

If instead I was looking for Marcel…

Channel
  .of(['Name': 'Marcel'], ['Name': 'Ashton'])
  .filter { it.Name == 'Marcel' }
  .ifEmpty { error("There is no name Bob in the channel") }
  .view { it['Name'] }

As you can see, the ifEmpty operator is what you’re probably looking for :wink: