0

Let's say I have the following webflux snippet:

.map(str -> str.split(","))
.OnErrorResume(...)

I want to make sure that split returns an array of EXACTLY x items. Otherwise I want to go into the OnErrorResume. Is there a webflux-y way to do that? filter will just remove the bad items, but that isn't what I want.

Do I need to expand the map to something like:

{
  String[] arr = str.split(",");
  if (arr.length != 3)
     return Mono.error();
  return arr;
}

Or is there something built in?

SledgeHammer
  • 7,338
  • 6
  • 41
  • 86

1 Answers1

1

Did you try handle method?

.map(str -> str.split(","))
.<String[]>handle((arr, sink) -> {
    if (arr.length == x)
         sink.next(arr);
    else
         sink.error(new ArrayLengthException());
   })
.onErrorResume(err -> Mono.just(...));
badger
  • 2,908
  • 1
  • 13
  • 32
  • handle loses the type if you have stuff after the .handle :(. – SledgeHammer May 03 '22 at 21:28
  • thanks. at that point, it's cleaner to do it in the single map :). too bad there isn't something nice like a .assert(arr -> arr.length == 3) :(. closest thing is .map(arr -> assert arr.length == 3) – SledgeHammer May 03 '22 at 21:49
  • 1
    @SledgeHammer great idea. I think there is not, take a look at this post (https://stackoverflow.com/questions/53595420/correct-way-of-throwing-exceptions-with-reactor) Oleh Dokuka is one of the main contributor to the project reactor and he stated all the methods for doing the job – badger May 03 '22 at 21:56
  • is it really necassary to use the `handle` function and not just a `flatMap` with an if statement that returns the rresult as a mono, or a Mono.error – Toerktumlare May 03 '22 at 22:54
  • @Toerktumlare feel free to edit the answer – badger May 04 '22 at 06:41