let's have method throws runtime exception. i'm using stream
call method on items in list.
class abc { public void dostuff(myobject myobj) { if (...) { throw new illegalstateexception("fire! fear! foes! awake!"); } // stuff... } public void dostuffonlist(list<myobject> myobjs) { try { myobjs.stream().foreach(abc:dostuff); } catch(aggregateruntimeexception??? are) { ... } } }
now want items in list processed, , runtime exceptions on individual items collected "aggregate" runtime exception thrown @ end.
in real code, making 3rd party api calls may throw runtime exceptions. want make sure items processed , errors reported @ end.
i can think of few ways hack out, such map()
function catches , returns exception (..shudder..). there native way this? if not, there way implement cleanly?
in simple case dostuff
method void
, care exceptions, can keep things simple:
myobjs.stream() .flatmap(o -> { try { abc.dostuff(o); return null; } catch (runtimeexception ex) { return stream.of(ex); } }) // stream of thrown exceptions. // can collect them list or reduce 1 exception .reduce((ex1, ex2) -> { ex1.addsuppressed(ex2); return ex1; }).ifpresent(ex -> { throw ex; });
however, if requirements more complicated , prefer stick standard library, completablefuture
can serve represent "either success or failure" (albeit warts):
public static void dostuffonlist(list<myobject> myobjs) { myobjs.stream() .flatmap(o -> completedfuture(o) .thenaccept(abc::dostuff) .handle((x, ex) -> ex != null ? stream.of(ex) : null) .join() ).reduce((ex1, ex2) -> { ex1.addsuppressed(ex2); return ex1; }).ifpresent(ex -> { throw new runtimeexception(ex); }); }
Comments
Post a Comment